#include "sk_dialog_gh.h"
#include "ui_sk_dialog_gh.h"
#include "pub_var.h"
#include <QDebug>
#include <QMessageBox>
#include <QAbstractItemView>
#include <QScrollBar>
#include <QSqlError>
#include <QFile>
#include <QPrinterInfo>
#include <QDateTime>
#include <QPageSize>
#include <QCryptographicHash>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>

const int MAX_DISTANCE_DAY = 90; //最大挂号间隔日期，用于判断复诊

Dialog_gh::Dialog_gh(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog_gh)
{
    ui->setupUi(this);

    initialed = false;
    //禁止dialog 窗口的默认按钮。
    ui->pbDefault->setVisible(false);

    //恢复窗口上次关闭时的位置和大小
    QSettings setIni("clin.ini", QSettings::IniFormat);
    QRect rct = setIni.value("windowState/gh").toRect();
    this->setGeometry(rct);
    qApp->processEvents();  //刷新界面显示


    ui->pbDsfz->setVisible(false);
    /*
    //使用读卡器原厂动态库
    //如果存在读卡器库，调用。
    qDebug()<<"检查路径中是否存在身份证读卡器dll。";
    QFile f;
    QString k = setIni.value("cardreader/use").toString();
    QString dllFile = pub::base_path;
    dllFile.append("/IDdlls/Termb.dll");

    if(f.exists(dllFile) && k == "1"){ //读卡器动态库存在且允许使用
        lib.setFileName("IDdlls/Termb");
        if(lib.load()){
            CVR_InitComm  = (pCVR_InitComm)lib.resolve("CVR_InitComm");//initialize
            CVR_Authenticate = (pCVR_Authenticate)lib.resolve("CVR_Authenticate") ;//卡认证;
            CVR_Read_Content = (pCVR_Read_Content)lib.resolve("CVR_Read_Content") ;//读卡操作。
            CVR_CloseComm = (pCVR_CloseComm)lib.resolve("CVR_CloseComm") ;//关闭连接;
            GetPeopleName = (pGetPeopleName)lib.resolve("GetPeopleName") ;//得到姓名信息
            GetPeopleSex = (pGetPeopleSex)lib.resolve("GetPeopleSex") ;//得到性别信息
            GetSexCode = (pGetSexCode)lib.resolve("GetSexCode") ;//得到性别信息
            GetPeopleBirthday = (pGetPeopleBirthday)lib.resolve("GetPeopleBirthday") ;//得到出生日期
            GetPeopleIDCode = (pGetPeopleIDCode)lib.resolve("GetPeopleIDCode") ;//得到卡号信息

            iniCardReader(setIni.value("cardreader/port").toInt());

        }else{
            QMessageBox::information(NULL, "注意","身份证读卡器动态库无效！");
            haveCardReader = false;
            ui->pbDsfz->setEnabled(false);
            qDebug()<<"身份证读卡器动态库无效！";
        }
    }else{
        ui->pbDsfz->setEnabled(false);
        qDebug()<<"身份证读卡器动态库不存在或被禁止使用！";
    }

*/
    qrm = new QSqlQuery(pub::db_m);
    qrmt = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    qro1 = new QSqlQuery(pub::db_o);

    //界面显示挂号科室的行数、列数
    dpRows = setIni.value("gh/rows").toInt();
    dpColumns = setIni.value("gh/columns").toInt();

    if(dpRows <1 || dpRows > 10 || dpColumns > 10 || dpColumns < 2)
    {
        QMessageBox::information(this,"警告","挂号待选科室行列数设置错误，使用默认5列1行！");
        dpRows = 1;
        dpColumns = 5 ;
    }

    //显示可用挂号科室
    sq = "select dept_code, dept_name, default_diag "
         " from com_department "
         " where valid_state = '1' and regdept_flag = '1'";
    qro->exec(sq);
    qDebug()<<"显示可用挂号科室"<<sq;

    ui->twDpList->setRowCount(dpRows);
    ui->twDpList->setColumnCount(dpColumns);
    for(int r = 0; r < dpRows ; r++)
    {
        for(int c = 0; c< dpColumns; c++)
        {
            if(qro->next())
            {
                ui->twDpList->setItem(r, c, new QTableWidgetItem(qro->value(1).toString()));
                sq = " select item_name "
                     " from com_dict_icpc "
                     " where nat_code = '" + qro->value(2).toString() + "' ";
                qrm->exec(sq);
                qDebug()<<"读取默认诊断 : "<<sq;
                if(qrm->next())
                {
                    dept_name_code << qro->value(1).toString()
                                      + "^" + qro->value(0).toString()
                                      + "^" + qro->value(2).toString()
                                      + "^" + qrm->value(0).toString();
                }
                else
                {
                    QMessageBox::information(this,"警告",qro->value(0).toString()
                                             + " 诊室默认诊断代码错误！");
                }
            }
            else
            {
                ui->twDpList->setItem(r,c,new QTableWidgetItem(""));
            }
        }
    }
    qDebug()<<"dept_name_code : "<<sq;

    //禁止列表滚动
    ui->twDpList->horizontalScrollBar()->setVisible(false);
    ui->twDpList->verticalScrollBar()->setVisible(false);

    //医生列表
    docRows = setIni.value("gh/drows").toInt();
    docColumns = setIni.value("gh/dcolumns").toInt();
    if(docRows <1 || docRows > 10 || docColumns > 10 || docColumns < 2)
    {
        QMessageBox::information(this,"警告","医生行列数设置错误，使用默认5列1行！");
        docRows = 1;
        docColumns = 5 ;
    }

    ui->twDocList->setRowCount(docRows);
    ui->twDocList->setColumnCount(docColumns);

    this->setWindowTitle("门诊挂号－当前用户－"+pub::usr_name);

    //挂号类别与挂号费列表
//    sq = "select  a.reglevl_name,  "
//         "b.reg_fee 挂号费, b.chck_fee 工本费, b.diag_fee 诊察费 , a.reglevl_code"
//         " from fin_opr_reglevel a , fin_opr_regfeeonpact b "
//         " where a.valid_state = '1' "
//         "and b.pact_code = '2'"
//         " and  a.reglevl_code = b.reglevl_code order by a.sort_id ";
    sq = "select lv.reglevl_name , 0 挂号费 , 0 工本费, "
         " nvl( UN.unit_price, 0) 诊察费 , lv.reglevl_code"
         " from FIN_OPR_REGLEVEL lv "
         " LEFT JOIN FIN_OPR_REGFEEITEM itm on ITM.REG_LEVEL = LV.REGLEVL_CODE"
         " LEFT JOIN FIN_COM_UNDRUGINFO un on itm.fee_code_his = UN.item_code"
         " where LV.valid_state = '1'"
         " order by lv.sort_id";
    qro->exec(sq);

    qDebug()<<"挂号类别与挂号费列表:"<<sq;

    QStringList t;
    QString s0,s4;
    float s1,s2,s3;
    while(qro->next())
    {
        s0 = qro->value(0).toString();//挂号类别名称
        s1 = qro->value(1).toFloat();//挂号费
        s2 = qro->value(2).toFloat();//工本
        s3 = qro->value(3).toFloat();//诊查
        s4 = qro->value(4).toString();//挂号类别代码
        t << s0;
        ghlb_ghf << s0 + "^" + QString::asprintf("%.1f",s1) + "^"
                 + QString::asprintf("%.1f",s2) + "^"
                 + QString::asprintf("%.1f",s3) + "^"
                 + QString::asprintf("%.1f",s1 + s2 + s3) + "^" + s4;
    }
    ui->cbbGhlb->addItems(t);

    //检查医保工作环境
    qDebug()<<"pub::useInsurance = "<<pub::useInsurance;
    if(pub::useInsurance)
    {
        ui->pbYbdk->setEnabled(true);
        ui->pbYbsm->setEnabled(true);
    }
    else
    {
        ui->pbYbdk->setEnabled(false);
        ui->pbYbsm->setEnabled(false);
    }

    //配置打印机
    QString printerName = setIni.value("gh/printer").toString();

    prt= new QPrinter(QPrinter::HighResolution);
    //prt= new QPrinter(QPrinter::ScreenResolution);
    prt->setPrinterName(printerName);

    sq = "select p_width,p_height from com_printer_setting where p_type = '挂号票' and p_item = '页面'";
    qrm->exec(sq);
    int w = 0, h = 0;

    if(qrm->next())
    {
        w = qrm->value(0).toInt();
        h = qrm->value(1).toInt();
    }
    else
    {
        QMessageBox::information(this,"错误","挂号票打印参数缺失！");
    }

    if( w<30 || h<30 )
    {
        QMessageBox::information(this,"错误","挂号票打印参数错误：页面数据无效！");
        w = 100 ;
        h = 100;
    }
    QSizeF sz = QSizeF(w,h);
    QPageSize psz(sz,QPageSize::Millimeter,"ghp",QPageSize::FuzzyMatch);
    prt->setPageSize(psz);

    QPageLayout pglot = QPageLayout(prt->pageLayout());
    //QRectF szf = pglot.fullRect(QPageLayout::Point);

    int dotPerInch = prt->physicalDpiX();
    ptScale = double(dotPerInch) / 25.4;

    prt->setOrientation(QPrinter::Portrait);      // 纵向打印
    //prt->setOrientation(QPrinter::Landscape);       //横向打印
    prt->setFullPage(true);
    pnt = new QPainter();

    on_pbClrScr_clicked(); //清屏

    qDebug()<<"提取下一个可用的就诊流水号";
    qro->exec("select seq_fin_clinicno.nextval from dual");
    qro->next();

    regClinicCode = qro->value(0).toString();

    if(regClinicCode.isEmpty())
    {
        QMessageBox::information(this,"错误","申请clinic_code失败！ ");
        return;
    }

    tm = new QTimer(this);
    connect(tm, SIGNAL(timeout()), this, SLOT(onTimeOut()));

    //初始化医保线程
    qDebug()<<"initialYb thread";
    ybBusiness = new ThreadYb(this);
    ybBusiness->moveToThread(&thread);
    qDebug()<<"thread start";
    thread.start();
    QMetaObject::Connection connRet =  connect(this, SIGNAL(opThread(int, QString)), ybBusiness, SLOT(doWork(int, QString)));
    Q_ASSERT(connRet);

    request.setUrl(QUrl(pub::hos_ybjy));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    sq = "create temporary table if not exists SUN_DOC_REG_COUNT "
         "(doc_name  VARCHAR(20),doc_code  VARCHAR(10),ord_count integer,see_count integer)";
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"错误"," SUN_DOC_REG_COUNT 创建表失败！");
    }

    timeBase = QDateTime::currentDateTime();    //分诊计算时间基准
    ui->teBase->setTime(QTime::currentTime());  //分诊计算时间基准

    ui->groupBox_2->setEnabled(false);

    max_card_no = 0;

    info_edit = new Sk_reg_info_edit() ;

    initialed = true;   //界面初始化标志。防止初始化未完成，发生界面事件。

}

Dialog_gh::~Dialog_gh()
{
    delete ui;
    delete info_edit;

    thread.quit();
    thread.wait();
}

void Dialog_gh::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/gh", QVariant(this->geometry()));
    emit destroyW( "dlg_gh" );
}

void Dialog_gh::handleRet(const int r, const QString o1,const QString o2)
{
    disconnect(ybBusiness, SIGNAL(resultReady(int, QString, QString)),
               this, SLOT(handleRet(int, QString, QString)));
    businessRetVal = r;
    businessRetStr1 = o1;
    businessRetStr2 = o2;
    businessFinish = true;
}

void Dialog_gh::on_twDocList_itemClicked(QTableWidgetItem * itm)
{
    qDebug()<<"通过医生列表单击提取医生代码";

    if(itm->text().isEmpty())
    {
        QMessageBox::information(this,"注意","医生姓名无效！");
        return;
    }

    docName = pub::getStr(itm->text() ," - ", 1);
    ui->leJzys->setText(docName);

    sq = "select empl_code from com_employee where valid_state = '1' ";
    sq += " and empl_name = '" + docName + "' ";
    qrm->exec(sq);
    qrm->next();
    docCode = qrm->value(0).toString();

    if(docCode.isEmpty())
    {
        QMessageBox::information(this,"注意","医生代码选择无效！");
        return;
    }
    qDebug()<<deptCode<<docName<<docCode;
}

void Dialog_gh::iniCardReader(int pt)
{
    qDebug()<<"初始化身份证读卡器";
    int ret = CVR_InitComm(pt);

    if(ret == 1)
    {
        //正常
        haveCardReader = true;
        return;
    }
    else if(ret == 2)
    {
        //端口错
        if(findCardReader())
        {
            //查到有效端口
            return;
        }
    }
    else if(ret == 0)
    {  //
        QMessageBox::information(NULL,"Note","身份证阅读器动态库运行中发生错误！");
    }
    else
    {
        QMessageBox::information(NULL,"Note","身份证阅读器错误，状态未知！");
    }
    haveCardReader = false;
    ui->pbDsfz->setEnabled(false);
}

bool Dialog_gh::findCardReader()
{
    qDebug()<<"检索身份证读卡器是否存在";
    int ret;

    for(int p=1001;p<1010;p++)
    {
        ret = CVR_InitComm(p);

        if(ret == 1)
        {
            haveCardReader = true;
            QSettings setIni("id.ini", QSettings::IniFormat);
            setIni.setValue("cardreader/port",QString::number(p));
            return true;
        }
    }
    QMessageBox::information(NULL,"Note","查询不到有效的身份证阅读器端口！");
    return false;
}

void Dialog_gh::on_leSfzh_returnPressed()
{
    qDebug()<<"手工录入身份证号检索挂号记录";
    ui->rbX->setChecked(true);  //input identify number, it must be cash regist.

    QString idno = ui->leSfzh->text().trimmed().toUpper();

    if(idno.length() < 18 )
    {
        //无效身份证
        return;
    }

    int s = idno.mid(16,1).toInt();  //gender flag bit
    if( s % 2 == 1)
    {
        ui->rbM->setChecked(true);
    }
    else
    {
        ui->rbFM->setChecked(true);
    }

    QStringList sl = pub::getNl(idno.mid(6, 8));

    if(!sl.isEmpty())
    {
        if(sl[0].toInt() >= 70)
        {
            //
            ui->cbbGhlb->setCurrentText("老年号");
        }
        ui->leNl->setText(sl[0]+sl[1]);
    }

    getRegRec("s0",ui->leSfzh->text().trimmed().toUpper(),"");
}

void Dialog_gh::postRequestFinished(QNetworkReply *)
{
    httpFinished = true;
    QVariant statusCode = rpl->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid())
    {
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        httpSuccess = false;
        return;
    }

    QNetworkReply::NetworkError err = rpl->error();

    if(err != QNetworkReply::NoError)
    {
        QMessageBox::warning(NULL,"注意",rpl->errorString());
        httpSuccess = false;
        return;
    }
    else
    {
        QByteArray bt = rpl->readAll();
        QString t = QString::fromLocal8Bit(bt);

        QJsonParseError json_error;
        QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
        if(json_error.error != 0 )
        {
            QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());
            httpSuccess = false;
            return;
        }
        qDebug()<< currentInfno+" outDoc "<<jsdc;
        QJsonObject jsob = jsdc.object();

        sq = "update com_business set tmstmp = now(), v_out = '"
                + jsdc.toJson(QJsonDocument::Compact)
             +"'  , infcode = "
                + QString::number(jsob.value("infcode").toInt())
                 +  "  where jyls = '" + currentMsgid + "'";

        if(!qrm->exec(sq))
        {
            QMessageBox::information(this,"错误","保存出参日志失败！");
            qDebug()<<sq;
        }

        if(jsob.value("infcode").toInt() != 0)
        {
            QString t = jsob.value("err_msg").toString();
            QMessageBox::warning(NULL,"注意",currentInfno+" 交易失败：" + t );
            httpSuccess = false;
            return;
        }

        if(currentInfno == "1101")
        {

            personBaseinfo = jsob.value("output").toObject().value("baseinfo").toObject();

            //读卡返回的个人险种排序无规律，需要人工查找指定的险种
            personInsuinfoA = jsob.value("output").toObject().value("insuinfo").toArray();
            QString insutype;
            bool found = false;
            for(int a = 0; a< personInsuinfoA.size(); a++)
            {

                insutype = personInsuinfoA[a].toObject().value("insutype").toString();

                if(personInsuinfoA[a].toObject().value("psn_insu_stas").toString() != "1")
                {
                    //非有效参保状态
                    continue;
                }
                //如果发现职工医保或居民医保，保存，退出循环

                qrmt->exec(" select name from com_dict_com "
                           " where dic_type = '险种' and code = '"+insutype+"'");
                if(qrmt->next())
                {
                    if( insutype == "310" )
                    {
                        otp_mulaid_used_flag_0 = pub::otp_mulaid_used_flag;
                    }
                    else
                    {
                        otp_mulaid_used_flag_0 = "0";
                    }
                    //pub::current_insu_type = insutype;
                    personInsuinfo = personInsuinfoA[a].toObject();
                    found = true;
                    ui->rbY->setText(qrmt->value(0).toString());
                    break;
                }
            }

            //如果未发现有效险种，读取第一个险种
            if(!found)
            {
                QMessageBox::information(this,"注意","医保卡没有有效的险种！");
                httpSuccess = false;
                return ;
                //personInsuinfo = jsob.value("output").toObject().value("insuinfo")[0].toObject();
            }

            personIdetinfo = jsob.value("output").toObject().value("idetinfo")[0].toObject();
        }
        else if(currentInfno == "2201")
        {
            ret2201 = jsob.value("output").toObject().value("data").toObject();
        }
        else if(currentInfno == "2001")
        {
            ret2001 = jsob.value("output").toObject().value("trtinfo").toObject();
        }
        else if(currentInfno == "2203A")
        {
        }
        else if(currentInfno == "2204")
        {
            ret2204 = jsob.value("output").toObject().value("result").toArray();
        }
        else if(currentInfno == "2206A")
        {
            ret2206setlinfo = jsob.value("output").toObject().value("setlinfo").toObject();
            ret2206setldetail = jsob.value("output").toObject().value("setldetail").toObject();
        }
        else if(currentInfno == "2207A")
        {
            ret2207setlinfo = jsob.value("output").toObject().value("setlinfo").toObject();
            ret2207setldetail = jsob.value("output").toObject().value("setldetail").toObject();
        }
        else if(currentInfno == "1901")
        {
            QJsonArray r = jsob.value("output").toObject().value("list").toArray();
            qDebug()<<r[0].toObject().value("type").toString();
        }

        httpSuccess = true;
    }
}

void Dialog_gh::readRetVal(QString s)
{
    Q_UNUSED(s)
    //读取扫码或读卡返回的医保数据
    mpPerson.clear();
    if(mdtrt_cert_type == "03")
    {
        //读卡
        if( "1" == pub::getStr(cardInfo,"|",1) )
        {   //0 社保卡， 1 老医保卡
            mpPerson["ybGrbh"] = pub::getStr(cardInfo,"|",8);//老医保卡,8卡号9社保号
            if(mpPerson["ybGrbh"].isEmpty())
            {
                mpPerson["ybGrbh"] = pub::getStr(cardInfo,"|",9);
            }
        }
        else
        {
            mpPerson["ybGrbh"] = pub::getStr(cardInfo,"|",4);//社保卡,4卡号3社保号
        }
    }
    if(mdtrt_cert_type == "02")
    {
        mpPerson["ybGrbh"] = pub::getStr(cardInfo,"|",2);   //身份证号
    }
    if(mdtrt_cert_type == "01")
    {
        //人员编号后10位即相当于医保卡号
        mpPerson["ybGrbh"] = personBaseinfo.value("psn_no").toString().right(10);

    }

    mpPerson["ybSfzh"] = personBaseinfo.value("certno").toString();
    mpPerson["ybXm"] = personBaseinfo.value("psn_name").toString();
    mpPerson["ybXb"] = personBaseinfo.value("gend").toString();
    mpPerson["ybCsrq"] = personBaseinfo.value("brdy").toString();
    mpPerson["ybSbkh"] = personBaseinfo.value("psn_no").toString();

    double zhye = personInsuinfo.value("balc").toDouble();

    mpPerson["ybZhye"] = QString::asprintf("%.2F", zhye);

    ui->leXm->setText(mpPerson["ybXm"]);

    if(mpPerson["ybXb"] == "1" || mpPerson["ybXb"] == "M")
    {
        ui->rbM->setChecked(true);
    }
    else
    {
        ui->rbFM->setChecked(true);
    }
    ui->leZhye->setText(mpPerson["ybZhye"]);
    ui->leYbkh->setText(mpPerson["ybGrbh"]);
    ui->leSfzh->setText(mpPerson["ybSfzh"]);
    QStringList sl = pub::getNl(mpPerson["ybCsrq"]);
    if(!sl.isEmpty())
    {
        if(sl[0].toInt() >= 70)
        {//
            ui->cbbGhlb->setCurrentText("老年号");
        }
        ui->leNl->setText(sl[0]+sl[1]);
    }

}

void Dialog_gh::printOut(QStringList p)
{
    qDebug()<<"打印挂号票";
    //参数格式： type^val
    //mode = 1 打印 item + val, mode = 0 只打印val
    QString item, val, mode,print_item,font;
    QFont ft=QFont();
    int top,left,width,height,size,position;

    pnt->begin(prt);
    foreach(QString i , p)
    {
        item = pub::getStr(i, "^", 1);
        val = pub::getStr(i, "^", 2);

        sq = "select p_top,p_left,p_width,p_height,p_font_name,p_font_size,"
             " p_position,p_mode,p_print_item from com_printer_setting "
             " where p_type = '挂号票' and p_item = '"+item+"'";
        if(!qrm->exec(sq))
        {
            QMessageBox::information(this,"error","SQL is : "+sq);
            return;
        }

        qrm->next();
        if(qrm->isNull(0))
        {
            //QMessageBox::information(this,"错误","找不到指定的项目名称："+item+" - "+val);
            continue;   //非打印项目
        }

        top = qrm->value(0).toInt();
        left = qrm->value(1).toInt();
        width = qrm->value(2).toInt();
        height = qrm->value(3).toInt();
        font = qrm->value(4).toString();
        size = qrm->value(5).toDouble();
        position = qrm->value(6).toInt();
        mode = qrm->value(7).toString();
        print_item = qrm->value(8).toString();
        //ft.setPointSize(int(ptScale * size));
        ft.setPixelSize(int(ptScale * size));
        ft.setFamily(font);

        pnt->setFont(ft);

        const QRect rect = QRect( left * ptScale, top * ptScale, width * ptScale, height * ptScale);
        QRect boundingRect;

        if(mode == "1")
        {
            pnt->drawText(rect, position, print_item + ":" + val, &boundingRect);
        }
        else
        {
            pnt->drawText(rect, position, val, &boundingRect);
        }
    }
    pnt->end();
}

void Dialog_gh::on_cbbGhlb_currentTextChanged(QString s)
{
    qDebug()<<"挂号类别变更";
    readGhf(s);
}

void Dialog_gh::readGhf(QString s)
{
    qDebug()<<"检索当前挂号类别挂号费" << s;
    foreach(QString i, ghlb_ghf)
    {
        if(pub::getStr(i,"^",1) == s)
        {
            qDebug() << i;
            ui->leYsk->setText(pub::getStr(i,"^",5));
            ghGhf = pub::getStr(i,"^",2);   //挂号费
            ghGbf = pub::getStr(i,"^",3);   //工本费
            ghZcf = pub::getStr(i,"^",4);   //诊查费
            ghType = pub::getStr(i,"^",1);  //当前挂号类别
            ghCode = pub::getStr(i,"^",6);  //类别代码
            ui->leGhfmx->setText("挂号费：" +  ghGhf +
                                 "，工本费：" + ghGbf +
                                 "，诊察费：" + ghZcf );
            break;
        }
    }
}

void Dialog_gh::on_pbClrScr_clicked()
{

    qDebug()<<"清屏，初始化窗口工作状态";
    ynfr = '1'; //设置默认状态为初诊
    pbGhClicked_finished = true;  //挂号操作成功标志，true申请新的发票号,false使用旧号
    mpPerson.clear();//个人信息
    setState("new");

    ui->leGhzs->clear();
    ui->leJzys->clear();
    ui->leNl->clear();
    ui->leSfzh->clear();
    ui->leXm->clear();
    ui->leYbkh->clear();
    ui->leBzh->clear();
    ui->leZhye->clear();
    ui->leYskX->clear();
    ui->leYskY->clear();
    ui->leYskJ->clear();
    ui->rbX->setChecked(true);
    ui->pbYjs->setEnabled(false);
    ui->cbIdNoCheck->setChecked(true);
    ui->cbbGhlb->setCurrentText("普通门诊");
    readGhf("普通门诊");

    for(int r = 0; r < docRows ; r++)
    {
        for(int c = 0; c< docColumns; c++)
        {
            QString s = "";
            ui->twDocList->setItem(r,c,new QTableWidgetItem(s));
        }
    }

    deptCode = "";
    deptName = "";
    ui->lbLastRec->setText("");

    ui->pbGhtp->setEnabled(false);
    ui->leBzh->setFocus();
    ui->leBzh->selectAll();

    if(pub::useInsurance)
    {
        ui->pbYbdk->setEnabled(true);
        ui->pbYbsm->setEnabled(true);
    }
    else
    {
        ui->pbYbdk->setEnabled(false);
        ui->pbYbsm->setEnabled(false);
    }
}

bool Dialog_gh::isValid()
{
    qDebug()<<"挂号信息有效性校验";

    if(docCode.isEmpty())
    {
        QMessageBox::warning(this,"错误","医生代码无效！");
        return false;
    }

    if(docName.isEmpty())
    {
        QMessageBox::warning(this,"错误","医生姓名无效！");
        return false;
    }

    if(deptCode.isEmpty())
    {
        QMessageBox::warning(this,"错误","诊室代码无效！");
        return false;
    }

    if(deptName.isEmpty())
    {
        QMessageBox::warning(this,"错误","诊室名称无效！");
        return false;
    }

    //姓名
    ui->leXm->setText((ui->leXm->text().trimmed()));
    if(ui->leXm->text().isEmpty())
    {
        QMessageBox::warning(this,"错误","姓名不可以为空！");
        return false;
    }
    else if(ui->leXm->text().length()>20)
    {
        QMessageBox::warning(this,"错误","姓名长度不可以超过20个字符！");
        return false;
    }

    //身份证号有效性验证
    if(ui->cbIdNoCheck->isChecked())
    {
        //身份证号长度验证
        ui->leSfzh->setText((ui->leSfzh->text().trimmed().toUpper()));
        if(ui->leSfzh->text().isEmpty())
        {
            QMessageBox::warning(this,"错误","身份证号不可以为空！");
            return false;
        }
        else if(ui->leSfzh->text().length()>18)
        {
            QMessageBox::warning(this,"错误","身份证号长度不可以超过18个字符！");
            return false;
        }

        char id[20];
        QByteArray id0 = ui->leSfzh->text().toLocal8Bit();
        memcpy(id, id0, id0.size() +1 );

        if(!pub::verifyIdCard(id))
        {
            QMessageBox::warning(this,"错误","身份证号有效性校验失败！");
            return false;
        }

        //身份证号与选定性别是否一致
        int s = ui->leSfzh->text().mid(16,1).toInt();  //gender flag bit
        if( s % 2 == 1)
        {
            if(ui->rbFM->isChecked())
            {
                QMessageBox::warning(this,"错误","身份证号性别与挂号性别不一致！");
                return false;
            }

        }
        else
        {
            if(ui->rbM->isChecked())
            {
                QMessageBox::warning(this,"错误","身份证号性别与挂号性别不一致！");
                return false;
            }
        }
    }

    //年龄
    if(ui->leNl->text().isEmpty())
    {
        QMessageBox::warning(this,"错误","年龄不可以为空！");
        return false;
    }

    //病志号
    ui->leBzh->setText((ui->leBzh->text().trimmed()));
    if(ui->leBzh->text().isEmpty())
    {
        QMessageBox::warning(this,"错误","病志号不可以为空！");
        return false;
    }
    else if(ui->leBzh->text().length()>10)
    {
        QMessageBox::warning(this,"错误","病志号长度不可以超过10个字符！");
        return false;
    }

    if( ui->leBzh->text().toInt() < 1)
    {
        QMessageBox::warning(this,"错误","病志号不可以输入数字以外的字符！");
        return false;
    }

    //就诊诊室
    if(ui->leGhzs->text().isEmpty() )
    {
        QMessageBox::information(this,"错误","诊室不可以为空！");
        return false;
    }

    sq = " select max(reg_date) from fin_opr_register "
         " where card_no = '%1' and dept_name = '%2' "
         " and valid_flag = '1' ";
    sq = sq.arg(pub::add0(ui->leBzh->text().trimmed(), 10))
            .arg(ui->leGhzs->text());

    qDebug()<<"读取挂号诊室的最后一次挂号时间";
    qDebug()<<sq<<"\n";

    qro->exec(sq);
    qro->next();

    if(!qro->isNull(0))
    {
        //非首次挂号
        QDate dt_reg = qro->value(0).toDate();
        QDate dt_cur = QDate::currentDate();

        int dt_distance = dt_reg.daysTo(dt_cur);

        if( dt_distance < MAX_DISTANCE_DAY)
        {
            //最后一次挂号日期距离当前日期小于复诊要求，认为是复诊
            ynfr = '0'; // 设置复诊标志
        }

        QDateTime dtt_reg = qro->value(0).toDateTime();
        QDateTime dtt_cur = QDateTime::currentDateTime();

        if( dt_distance < 4)
        {
            //最后一次挂号日期距离当前日期在 3 天之内
            //ICPC要求三天内不可以因相同疾病挂相同诊室的号
            //挂相同诊室可以因为不同疾病，所以需要人工确认
            QMessageBox::StandardButton bt;
            bt = QMessageBox::question(this, "注意", "三天内有过相同诊室挂号记录，"
                                                   "\n请确认此次挂号就诊原因与前次挂号不同！");
            if(bt != QMessageBox::Yes)
            {
                return false;
            }
        }
    }

    ui->leBzh->setText(pub::add0(ui->leBzh->text().trimmed(),10) );//如病志号格式不规范，修正。
    if(ui->rbY->isChecked())
    {
        //医保
        if(ui->leYbkh->text().trimmed().isEmpty() )
        {
            QMessageBox::information(this,"错误","医保挂号，医保卡号不可以为空！");
            return false;
        }
    }

    QRegExp re("^\\d*$");
    if(re.exactMatch(ui->leNl->text()))
    {
        //年龄未输入单位，默认为"岁"
        ui->leNl->setText(ui->leNl->text()+"岁");
    }

    QString b = pub::getBirth(ui->leNl->text());
    if(b.isEmpty())
    {
        //录入无效年龄
        //QMessageBox::information(this,"错误","录入了无效的年龄！");
        return false;
    }

    //是否存在同日同诊室挂号记录
    sq = " select r.name from fin_opr_register r "
         " where r.valid_flag = '1' and ";

    if(ui->cbIdNoCheck->isChecked())
    {
        //身份证号有效，以身份证号为唯一依据
        sq = sq + " r.idenno = '"
                + ui->leSfzh->text() + "' ";
    }
    else
    {
        //身份证号无效，以病志号为唯一依据
        sq = sq + " r.card_no = '"
                + ui->leBzh->text() + "' ";
    }

    sq = sq + " and r.dept_code = '"
            + deptCode + "' and trunc(reg_date) = trunc(sysdate) ";
    qro->exec(sq);

    qro->next();
    if(!qro->isNull(0))
    {
        qDebug()<<qro->value(0).toString();
        QMessageBox::information(this,"错误","同日相同诊室不可以重复挂号！");
        return false;
    }

    if(displayMode == "new")
    {

    }

    /*
     * 2025-4-29
     * 新病志号以前手工录入，现为系统自动生成，已经不存在重复使用的可能性
    //病志号是否已经使用
    sq = "select r.name from fin_opr_register r "
         " where r.valid_flag = '1' and r.card_no = '" + ui->leBzh->text() + "' and rownum = 1";
    qro->exec(sq);

    qro->next();

    if(!qro->isNull(0) && qro->value(0).toString() != ui->leXm->text().trimmed()){
        //病志号关联的姓名非空，且不等于当前录入的姓名
        QMessageBox::information(this,"错误","病志号 " + ui->leBzh->text() + " 已经被患者 " + qro->value(0).toString() + " 使用！");
        return false;
    }
    */

    qDebug()<<"通过验证";
    return true;
}

QString Dialog_gh::ybGh()
{

    QJsonDocument d;    //清空QJsonObject之用
    QJsonObject in; //入参
    QJsonObject inpu,inpud; // 入参 input 段

    putBaseIn(in, "2201");

    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());   //人员编号
    inpu.insert("insutype", personInsuinfo.value("insutype").toString());   //险种类型
    inpu.insert("begntime",QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//	开始时间
    inpu.insert("mdtrt_cert_type",mdtrt_cert_type);//	就诊凭证类型
    if(mdtrt_cert_type == "03")
    {
        //读卡
        if( "1" == pub::getStr(cardInfo,"|",1) )
        {
            //0 社保卡， 1 老医保卡
            if(pub::getStr(cardInfo,"|",8).isEmpty())
            {
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",9) + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            }
            else
            {
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",8) + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            }
        }
        else
        {
            inpu.insert("mdtrt_cert_no",pub::getStr(cardInfo,"|",4) + "|" + busiCardInfo);//	就诊凭证编号
        }

    }
    else if (mdtrt_cert_type == "02")
    {
        inpu.insert("mdtrt_cert_no",pub::getStr(cardInfo,"|",2) + "|" + busiCardInfo);//	就诊凭证编号
    }
    else if(mdtrt_cert_type == "01")
    {
        //扫码
        inpu.insert("mdtrt_cert_no", retScan.value("ecToken").toString());//	就诊凭证编号
    }

    inpu.insert("ipt_otp_no", regClinicCode);//	住院/门诊号
    sq = "select si_code, empl_name from com_doctor_compare where empl_code = '" + docCode + "'";
    qro->exec(sq);
    qro->next();
    docCodeYb = qro->value(0).toString();

    inpu.insert("atddr_no", docCodeYb);//	医师编码
    inpu.insert("dr_name", qro->value(1).toString());//	医师姓名
    inpu.insert("dept_code", deptCode);//	科室编码
    inpu.insert("dept_name", deptName );//	科室名称
    inpu.insert("caty", "0");//	科别

    inpud.insert("data",inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);

    sq = "update com_business set v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
         " where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    qDebug()<<currentInfno + " indoc"<<indoc;

    QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
    connect(naManager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(postRequestFinished(QNetworkReply*)));

    httpSuccess = false;
    httpFinished = false;
    rpl = naManager->post(request, indoc.toJson());
    qDebug()<<"request " + currentInfno + " ...";
    statusMsg = "交易 " + currentInfno + " 。。。";

    while(true)
    {
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty())
        {
            ui->lbLastRec->setText(statusMsg);
        }
        else
        {
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(httpFinished)
        {
            qDebug()<<"return request 2201 ...";
            break;
        }
    }

    if(!httpSuccess)
    {
        // failure then stop operation;
        return "";//

    }

    in = d.object();
    inpu = d.object();
    inpud = d.object();
    putBaseIn(in, "2203A");

    inpu.insert("mdtrt_id", ret2201.value("mdtrt_id").toString());   //就诊ID
    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());   //人员编号
    //inpu.insert("med_type","12");//	医疗类别
    inpu.insert("med_type","11");//	医疗类别
    inpu.insert("begntime", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//	开始时间

    QJsonObject t2203exp;
    t2203exp.insert("trum_flag","0");  //   外伤标志
    t2203exp.insert("rel_ttp_flag","0");    //涉及第三方标志
    t2203exp.insert("otp_mulaid_used_flag", otp_mulaid_used_flag_0); //共济标志，  0共济，1不共济。
    //t.insert("mdtrt_grp_type","0");  //就诊人群类型
    //t.insert("elec_bill_code","0");  //电子票据代码
    //t.insert("elec_billno_code","0"); //电子票据号码
    //t.insert("otp_er_refl_flag","0");    //门诊急诊转诊标志

    inpu.insert("exp_content", t2203exp);//	字段扩展

    inpud.insert("mdtrtinfo",inpu);
    //in.insert("input", inpud);

    inpu = d.object();      //临时变量清空

    //inpu = d.object();
    //    inpud = d.object();

    inpu.insert("diag_type", "1");   //诊断类别：1 西医主要诊断， 2 中医主病诊断	3 中医主证诊断
    inpu.insert("diag_srt_no", 1);   //诊断排序号
    inpu.insert("diag_code", default_diag_code); //诊断代码
    inpu.insert("diag_name", default_diag_name);//诊断名称
    inpu.insert("diag_dept", deptName);   //诊断科室
    inpu.insert("dise_dor_no", docCodeYb);   //诊断医生编码
    inpu.insert("dise_dor_name", docName);//诊断医生姓名
    inpu.insert("diag_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//诊断时间
    inpu.insert("vali_flag", "1");//有效标志

    QJsonArray djsar;
    djsar<<inpu;

    inpud.insert("diseinfo", djsar);


    in.insert("input", inpud);

    indoc.setObject(in);
    qDebug()<< currentInfno + " indoc"<<indoc;

    sq = "update com_business set v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
         " where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    httpSuccess = false;
    httpFinished = false;
    rpl = naManager->post(request, indoc.toJson());
    qDebug()<<"request " + currentInfno + " ...";
    statusMsg = "交易 " + currentInfno + " 。。。";

    while(true)
    {
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty())
        {
            ui->lbLastRec->setText(statusMsg);
        }
        else
        {
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(httpFinished){
            qDebug()<<"return request " + currentInfno + " ...";
            break;
        }
    }

    if(!httpSuccess){// failure then stop operation;
        return "";//
    }


    //挂号费用上传
    in = d.object();
    inpu = d.object();
    inpud = d.object();
    putBaseIn(in, "2204");

    QJsonArray jsar;
    QString feedetl_sn = "0";
    qro->exec("select max(Balance_No) from fin_ipr_siinmaininfo "
              " where clinic_code = '" + regClinicCode + "'");
    if(qro->next()){
        feedetl_sn = QString::number(qro->value(0).toInt() + 1);
    }


    inpu.insert("feedetl_sn", feedetl_sn);//	费用明细流水号
    inpu.insert("mdtrt_id", ret2201.value("mdtrt_id").toString());//	就诊ID
    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());//	人员编号
    inpu.insert("chrg_bchno", cur_fph);//	收费批次号
    //inpu.insert("rxno", personBaseinfo.value("psn_no").toString());//	处方号
    inpu.insert("rx_circ_flag", "0");//	外购处方标志
    inpu.insert("fee_ocur_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//	费用发生时间
    qro->exec("select fee_code_center, fee_code_his from FIN_OPR_REGFEEITEM"
              " where fee_name ='诊查费'");
    qro->next();

    inpu.insert("med_list_codg", qro->value(0).toString());//	医疗目录编码-00110200001000003
    inpu.insert("medins_list_codg", qro->value(1).toString() );//	医药机构目录编码
    //inpu.insert("det_item_fee_sumamt", ui->leYsk->text().toDouble());//	明细项目费用总额
    inpu.insert("det_item_fee_sumamt", ui->leYsk->text());//	明细项目费用总额
    inpu.insert("cnt", 1);//	数量
    //inpu.insert("pric", ui->leYsk->text().toDouble());//	单价
    inpu.insert("pric", ui->leYsk->text());//	单价
    inpu.insert("bilg_dept_codg", deptCode);//	开单科室编码
    inpu.insert("bilg_dept_name", deptName);//	开单科室名称
    inpu.insert("bilg_dr_codg", docCodeYb);//	开单医生编码
    inpu.insert("bilg_dr_name", docName);//	开单医师姓名
    inpu.insert("hosp_appr_flag", "1");//	医院审批标志

    jsar.append(inpu);

    inpud.insert("feedetail",jsar);
    in.insert("input", inpud);

    indoc.setObject(in);
    qDebug()<< currentInfno + " indoc"<<indoc;

    sq = "update com_business set v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
         " where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    httpSuccess = false;
    httpFinished = false;
    rpl = naManager->post(request, indoc.toJson());
    qDebug()<<"request " + currentInfno + " ...";
    statusMsg = "交易 " + currentInfno + " 。。。";

    while(true)
    {
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty())
        {
            ui->lbLastRec->setText(statusMsg);
        }
        else
        {
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();

        if(httpFinished)
        {
            qDebug()<<"retrun request " + currentInfno + " ...";
            break;
        }
    }

    if(!httpSuccess){// failure then stop operation;
        return "";//
    }


    //医保结算
    in = d.object();
    inpu = d.object();
    inpud = d.object();
    putBaseIn(in, "2207A");

    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());//人员编号
    inpu.insert("mdtrt_cert_type", mdtrt_cert_type);//	就诊凭证类型

    if(mdtrt_cert_type == "03")
    {
        if( "1" == pub::getStr(cardInfo,"|",1) )
        {
            //0 社保卡， 1 老医保卡
            if(pub::getStr(cardInfo,"|",8).isEmpty())
            {
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",9) + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            }
            else
            {
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",8) + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            }

        }
        else
        {
            inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",4) + "|" + busiCardInfo);   //社保卡,4卡号3社保号
        }
    }
    else if(mdtrt_cert_type == "02")
    {
        inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",2) + "|" + busiCardInfo);

    }
    else if(mdtrt_cert_type == "01")
    {
        inpu.insert("mdtrt_cert_no", retScan.value("ecToken").toString());//	就诊凭证编号
    }

    //inpu.insert("med_type", "12");//医疗类别    12,挂号
    inpu.insert("med_type","11");//	医疗类别
    inpu.insert("medfee_sumamt", ui->leYsk->text());//	医疗费总额
    inpu.insert("psn_setlway", "01");//	个人结算方式
    inpu.insert("mdtrt_id", ret2201.value("mdtrt_id").toString());//	就诊ID
    inpu.insert("chrg_bchno", cur_fph);//	收费批次号
    inpu.insert("acct_used_flag","1" );//个人账户使用标志
    inpu.insert("insutype", personInsuinfo.value("insutype").toString());//险种类型

    QJsonObject t;
    t.insert("deve_flag","OwnSoft");
    t.insert("dise_reim_mon","");
    t.insert("otp_mulaid_used_flag",otp_mulaid_used_flag_0); //共济标志，  0共济，1不共济。

    inpu.insert("exp_content", t);//	字段扩展
    inpud.insert("data",inpu);
    in.insert("input", inpud);

    indoc.setObject(in);
    qDebug()<<" 2207 indoc"<<indoc;

    sq = "update com_business set v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
         " where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    httpSuccess = false;
    httpFinished = false;
    rpl = naManager->post(request, indoc.toJson());
    qDebug()<<"request " + currentInfno + " ...";
    statusMsg = "交易 " + currentInfno + " 。。。";
    while(true)
    {
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty())
        {
            ui->lbLastRec->setText(statusMsg);
        }
        else
        {
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();

        if(httpFinished)
        {
            qDebug()<<"retrun request " + currentInfno + " ...";
            break;
        }
    }

    if(httpSuccess)
    {
        return "success";
    }
    else
    {
        return "";
    }
}

void Dialog_gh::resizeEvent(QResizeEvent *event)
{
    if(!initialed){
        return;
    }
    Q_UNUSED(event);

    int columnWidth=(ui->twDpList->width()-3)/dpColumns;
    for(int c = 0; c<dpColumns; c++)
    {
        ui->twDpList->setColumnWidth(c,columnWidth);
    }

    int rowHeight=(ui->twDpList->height()-3)/dpRows;
    for(int r = 0; r< dpRows; r++)
    {
        ui->twDpList->setRowHeight(r,rowHeight);
    }

    columnWidth=(ui->twDocList->width()-3)/docColumns;
    for(int c = 0; c<docColumns; c++)
    {
        ui->twDocList->setColumnWidth(c,columnWidth);
    }

    rowHeight=(ui->twDocList->height()-3)/docRows;
    qDebug()<<rowHeight<<ui->twDocList->height()<<docRows;
    for(int r = 0; r< docRows; r++)
    {
        ui->twDocList->setRowHeight(r,rowHeight);
    }
    qDebug()<<"窗口界面设定完成";
}

void Dialog_gh::setState(QString s)
{
    qDebug()<<"设置界面工作模式"<<s;
    if(s == "new")
    {
        //
        qDebug()<<"新病志号，所有项目均可录入";
        displayMode = "new";
        ui->leNl->setReadOnly(false);
        ui->leSfzh->setReadOnly(false);
        ui->leXm->setReadOnly(false);
        ui->grpSex->setEnabled(true);
        ui->pb_generate_card_no->setEnabled(true);
        ui->leBzh->setEnabled(true);
    }
    else if(s == "retbzh")
    {
        //
        qDebug()<<"病志号检索有效，基础项目不可录入";
        displayMode = "retbzh";

        if(!ui->leBzh->text().trimmed().isEmpty())
        {
            ui->pb_generate_card_no->setEnabled(false);
            ui->leBzh->setEnabled(false);
        }

        if(ui->leNl->text().isEmpty())
        {
            ui->leNl->setReadOnly(false);
        }
        else
        {
            ui->leNl->setReadOnly(true);
        }

        if(ui->leSfzh->text().trimmed().length() < 18)
        {
            ui->leSfzh->setReadOnly(false);
        }
        else
        {
            ui->leSfzh->setReadOnly(true);
        }
//        ui->leXm->setReadOnly(true);
        if(mpPerson["ybXb"].isEmpty())
        {
            ui->grpSex->setEnabled(true);
        }
        else
        {
            ui->grpSex->setEnabled(false);
        }
    }
}

void Dialog_gh::getRegRec(QString s, QString n1, QString n2)
{

    //2024-3-4
    Q_UNUSED(n2)
    //读身份证或读医保卡，均以身份证号作为唯一检索依据

    QString sq;
    if(s == "y")
    {
        //医保卡
        ui->rbY->setChecked(true);
    }
    else if( s == "s" || s == "s0")
    {
        //身份证,s 机读， s0手工录入。
        ui->rbX->setChecked(true);
    }
    else
    {
        QMessageBox::information(this,"注意","getRegRec 参数错误！");
        qDebug()<<"getRegRec 参数错误";
        return;
    }

    sq = "select card_no ,mcard_no from fin_opr_register where idenno = '"
            + n1 +"' order by reg_date desc";
    qDebug()<<"检索身份证关联的病志号："<<sq;
    qro->exec(sq);

    if(qro->next())
    {
        //取得有效病志号
        ui->leBzh->setText(qro->value(0).toString());
        //leBzhRet();
        on_leBzh_returnPressed();
        setState("retbzh"); //有效返回的基础数据不允许修改
        return;
    }

    if( s != "s0")
    {
        //新数据，非手工录入身份证号，不允许修改
        setState("retbzh");
    }
}



void Dialog_gh::selectDoctor()
{

    qDebug()<<"诊室信息："<<deptName<<", "<<deptCode;

    sq = "select distinct empl_name from com_loginlog where dept_code ='"
            + deptCode + "' and login_date>trunc(sysdate) order by empl_name";
    qro->exec(sq);

    qDebug()<<"提取诊室医生信息："<<sq;


    QStringList nmlst;

    if(!qro->next())
    {
        //未提取到医生登录信息
        qDebug()<<"指定诊室无有效的医生! ";
        QMessageBox::information(this,"注意","指定的科室没有有效医生，请与诊室核对后再挂号！");
        ui->leGhzs->clear();
        ui->leJzys->clear();
        return;
    }
    else
    {
        //之前为了判断表是否为空，已经把游标定到0号记录
        while(true)
        {
            QString empl_name = qro->value(0).toString();
            //防止未正常退出登录记录干扰
            //检索医生最后一次登入记录

            //20240827 修正登入登出管理方式，正常操作不会存在未登出记录
            //sq = "select case when logout_date is not null then '' else empl_name end "
            //     "from com_loginlog where login_date > trunc(sysdate) and empl_name = '"
            //        + empl_name + "' and dept_code = '" + deptCode + "' " ;// order by login_date desc
            sq = "select empl_name from com_loginlog where login_date > trunc(sysdate) and logout_date is null "
                 " and empl_name = '" + empl_name + "' and dept_code = '" + deptCode + "' " ;
            qro1->exec(sq);

            qDebug()<<"检索医生本日是否存在未登出的记录"<<sq;
            qro1->next();
            if(!qro1->value(0).toString().isEmpty())
            {
                nmlst << qro1->value(0).toString();
            }

            if(!qro->next())
            {
                break;
            }
        }
    }

    qDebug()<<"doctor name list is "<<nmlst;

    qDebug()<<"清空用于计算分配接诊医生的临时表";
    qrm->exec("delete from sun_doc_reg_count");

    for(int i = 0; i < nmlst.size(); i++ )
    {
        sq = "insert into sun_doc_reg_count (doc_name, doc_code, ord_count, see_count)";
        sq += " values('" + nmlst[i] + "', (select empl_code from com_employee where";
        sq += " empl_name = '" + nmlst[i] + "' and valid_state = '1' limit 1 ), 0 , 0)";      //存储临时表
        qrm->exec(sq);
    }

    qDebug()<<"分配默认接诊医生:";
    //分配策略：1.谁有空。 2.都有空，谁接的少。 3.每天分两段计算，13:30 为时间分隔点。
    //2021-8-16
    //患者量不大，且为防止挂号未就诊不及时退号情况，取消 分配策略 1 。
    //QTime cur = QTime::currentTime();
    //QTime sep = QTime::fromString("13:30:00","HH:mm:ss");
    //QString tmp;
    //if(cur > sep){
    //    tmp = "r.reg_date > trunc(sysdate) + 9/16";
    //}else{
    //    tmp = "r.reg_date > trunc(sysdate)";
    //}

    //2024-5-18
    //时间基准根据需要调整
    if(ui->teBase->time() != timeBase.time())
    {
        //界面显示时间基准与内存记录时间基准不一致
        ui->teBase->setTime(timeBase.time());
    }
    QString tmp;
    tmp = "r.reg_date > to_date('" + timeBase.toString("yyyy-MM-dd HH:mm:ss") + "','yyyy-mm-dd hh24:mi:ss') ";

    //检索已接诊数量
    //根据操作员选择，确定使用挂号数量还是接诊数量进行计算排序
    QString codeName;//挂号或接诊
    if(ui->rbReg->isChecked())
    {
        codeName = "r.doct_code";
    }
    else
    {
        codeName = "r.see_docd";
    }
    qro->prepare("select " + codeName +", count(*) c from fin_opr_register r"
                 " where " + tmp + " and r.trans_type = '1' "
                 " and r.valid_flag ='1' and r.dept_code = '"+deptCode+"' "
                 " group by " + codeName  );

    qro->exec();
    qDebug()<<"count regist number : "<< qro->lastQuery();
    qDebug()<<"deptCode : "<<deptCode;
    while(qro->next())
    {
        if(!qro->value(0).toString().isEmpty())
        {
            //sun_doc_reg_count里只保存当前可用医生。
            qrmt->exec("update sun_doc_reg_count set see_count = " + qro->value(1).toString() +
                       " where doc_code = '"+ qro->value(0).toString() +"'");

            qDebug()<<"检索已接诊数量"<<qro->value(0).toString()<<qro->value(1).toString();

        }
    }

    qrm->exec("select doc_name,doc_code,see_count from sun_doc_reg_count order by see_count");

    //填充医生列表
    QString s = "";
    for(int r = 0; r < docRows ; r++)
    {
        for(int c = 0; c< docColumns; c++)
        {
            if(qrm->next())
            {
                s = qrm->value(0).toString() + " - " + qrm->value(2).toString();
            }
            else
            {
                s = "";
            }
            ui->twDocList->setItem(r,c,new QTableWidgetItem(s));
        }
    }

    //默认挑选接诊医生
    qrm->first();
    docCode = qrm->value(1).toString();
    docName = qrm->value(0).toString();
    ui->leJzys->setText(docName);

    qDebug()<<"regist select doctor is : " << docCode<<docName;

}

void Dialog_gh::on_pbExit_clicked()
{
    qDebug()<<"退出挂号";
    this->close();
}

void Dialog_gh::on_pbRePrint_clicked()
{
    if(reg_item_list.isEmpty())
    {
        QMessageBox::information(this,"错误","没有可打印的内容！");

        return;
    }
    printOut(reg_item_list);

}

void Dialog_gh::onTimeOut()
{
    if(ui->lbLastRec->text().isEmpty())
    {
        ui->lbLastRec->setText(statusMsg);
    }
    else
    {
        ui->lbLastRec->setText("");
    }
    qApp->processEvents();  //刷新显示
}

void Dialog_gh::on_pbGhtp_clicked()
{
    //只允许现金患者进行换号操作
    //医保换号可能会引起结算混乱

    if(mpPerson["previous_doct_name"] == docName
            && mpPerson["previous_dept_name"] == deptName
            && mpPerson["previous_patient_name"] == ui->leXm->text().trimmed() )
    {
        QMessageBox::warning(this,"注意","无可变更内容！");
        return;
    }

    QString info ;
    if(mpPerson["previous_patient_name"] != ui->leXm->text().trimmed() )
    {
        info.append("患者姓名： " + mpPerson["previous_patient_name"] + " -> " + ui->leXm->text().trimmed() +"\n");
    }

    if(mpPerson["previous_dept_name"] != deptName)
    {
        info.append("就诊科室： " + mpPerson["previous_dept_name"] + " -> " + deptName +"\n") ;
    }

    if(mpPerson["previous_doct_name"] != docName)
    {
        info.append("看诊医生： " + mpPerson["previous_doct_name"] + " -> " + docName +"\n") ;
    }

    info.append("确定要进行挂号信息变更？");

    QMessageBox:: StandardButton result
            = QMessageBox::warning(this, "注意", info, QMessageBox::Yes|QMessageBox::No);
    if(result != QMessageBox::Yes)
    {
        return;
    }

    sq = "update fin_opr_register set name = '%1', "
         "dept_code = '%2', dept_name = '%3',doct_code = '%4', "
         "doct_name = '%5' where rowid = '%6'";
    sq = sq.arg(ui->leXm->text().trimmed())
            .arg(deptCode)
            .arg(deptName)
            .arg(docCode)
            .arg(docName)
            .arg(mpPerson["rowid"]);

    qDebug()<<"变更挂号信息："<<sq<<"\n";

    if(!qro->exec(sq))
    {
        QMessageBox::warning(this,"注意","挂号变更操作失败！");
    }
    else
    {
        QMessageBox::information(this,"注意","挂号变更操作完成！");
    }

    on_pbClrScr_clicked(); //清屏
}

void Dialog_gh::putBaseIn( QJsonObject &in, QString code)
{
    currentMsgid = pub::getYbStrJ(code, regClinicCode);   //
    if(currentMsgid.isEmpty())
    {
        QThread::msleep(1000);
        currentMsgid = pub::getYbStrJ(code, "CLINIC_CODE");   //
        if(currentMsgid.isEmpty())
        {
            QMessageBox::information(this,"note",  code + " 申请交易流水号失败！");
            return ; //未能成功申请交易流水号
        }
    }

    currentInfno = code;

    if(code == "2207A")
    {
        msgid2207 = currentMsgid;
    }

    in.insert("infno", code);
    in.insert( "msgid", currentMsgid);
    in.insert("mdtrtarea_admvs", pub::hos_insuplc);

    if(!personInsuinfo.value("insuplc_admdvs").toString().isEmpty())
    {
        in.insert("insuplc_admdvs",personInsuinfo.value("insuplc_admdvs").toString());
    }

    in.insert("insuplc_admdvs","210100");
    in.insert("recer_sys_code", "OwnSoft");
    in.insert("dev_no","");
    in.insert("dev_safe_info","");
    in.insert("cainfo", pub::hos_secretcode);
    in.insert("signtype","");
    in.insert("infver", "V1.0");
    in.insert("opter_type", "1");
    in.insert("opter", pub::usr_code);
    in.insert("opter_name", pub::usr_name);
    in.insert("inf_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
    in.insert("fixmedins_code", pub::hos_ybbh);
    in.insert("fixmedins_name", pub::hos_name);
    in.insert("sign_no", pub::sign_no);

}

void Dialog_gh::on_pbYjs_clicked()
{

    QJsonDocument d;    //清空QJsonObject之用
    QJsonObject in; //入参
    QJsonObject inpu,inpud; // 入参 input 段

    putBaseIn(in, "2201");

    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());   //人员编号
    inpu.insert("insutype", personInsuinfo.value("insutype").toString());   //险种类型
    inpu.insert("begntime",QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//	开始时间
    inpu.insert("mdtrt_cert_type",mdtrt_cert_type);//	就诊凭证类型

    if(mdtrt_cert_type == "03")
    {
        if( "1" == pub::getStr(cardInfo,"|",1) )
        {
            //0 社保卡， 1 老医保卡
            if(pub::getStr(cardInfo,"|",8).isEmpty())
            {
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",9) + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            }
            else
            {
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",8) + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            }

        }
        else
        {
            inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",4) + "|" + busiCardInfo);   //社保卡,4卡号3社保号
        }
    }
    else if(mdtrt_cert_type == "02")
    {
        inpu.insert("mdtrt_cert_no",pub::getStr(cardInfo,"|",2) + "|" + busiCardInfo);//	就诊凭证编号
    }
    else if(mdtrt_cert_type == "01")
    {
        inpu.insert("mdtrt_cert_no", retScan.value("ecToken").toString());//	就诊凭证编号
    }

    inpu.insert("ipt_otp_no", regClinicCode);//	住院/门诊号
    sq = "select si_code, empl_name from com_doctor_compare where empl_code = '" + docCode + "'";
    qro->exec(sq);
    qro->next();
    docCodeYb = qro->value(0).toString();

    inpu.insert("atddr_no", docCodeYb);//	医师编码
    inpu.insert("dr_name", qro->value(1).toString());//	医师姓名
    inpu.insert("dept_code", deptCode);//	科室编码
    inpu.insert("dept_name", deptName );//	科室名称
    inpu.insert("caty", "0");//	科别

    inpud.insert("data",inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);

    sq = "update com_business set v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
         " where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    qDebug()<<currentInfno + " indoc"<<indoc;

    QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
    connect(naManager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(postRequestFinished(QNetworkReply*)));

    httpSuccess = false;
    httpFinished = false;
    rpl = naManager->post(request, indoc.toJson());
    qDebug()<<"request " + currentInfno + " ...";
    statusMsg = "交易 " + currentInfno + " 。。。";

    while(true)
    {
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty())
        {
            ui->lbLastRec->setText(statusMsg);
        }
        else
        {
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(httpFinished)
        {
            qDebug()<<"return request 2201 ...";
            break;
        }
    }

    if(!httpSuccess)
    {
        // failure then stop operation;
        return ;
    }

    in = d.object();
    inpu = d.object();
    inpud = d.object();
    putBaseIn(in, "2203A");

    inpu.insert("mdtrt_id", ret2201.value("mdtrt_id").toString());   //就诊ID
    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());   //人员编号
    //inpu.insert("med_type","12");//	医疗类别
    inpu.insert("med_type","11");//	医疗类别
    inpu.insert("begntime", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//	开始时间

    QJsonObject t2203exp;

    t2203exp.insert("trum_flag","0");  //   外伤标志
    t2203exp.insert("rel_ttp_flag","0");    //涉及第三方标志
    t2203exp.insert("otp_mulaid_used_flag", otp_mulaid_used_flag_0); //共济标志，  0共济，1不共济。

    inpu.insert("exp_content", t2203exp);//	字段扩展
    inpud.insert("mdtrtinfo",inpu);

    inpu = d.object();      //临时变量清空

    inpu.insert("diag_type", "1");   //诊断类别：1 西医主要诊断， 2 中医主病诊断	3 中医主证诊断
    inpu.insert("diag_srt_no", 1);   //诊断排序号
    inpu.insert("diag_code", default_diag_code); //诊断代码
    inpu.insert("diag_name", default_diag_name);//诊断名称
    inpu.insert("diag_dept", deptName);   //诊断科室
    inpu.insert("dise_dor_no", docCodeYb);   //诊断医生编码
    inpu.insert("dise_dor_name", docName);//诊断医生姓名
    inpu.insert("diag_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//诊断时间
    inpu.insert("vali_flag", "1");//有效标志

    QJsonArray djsar;

    djsar<<inpu;

    inpud.insert("diseinfo", djsar);


    in.insert("input", inpud);

    indoc.setObject(in);
    qDebug()<< currentInfno + " indoc"<<indoc;

    sq = "update com_business set v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
         " where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    httpSuccess = false;
    httpFinished = false;
    rpl = naManager->post(request, indoc.toJson());
    qDebug()<<"request " + currentInfno + " ...";
    statusMsg = "交易 " + currentInfno + " 。。。";
    while(true)
    {
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty())
        {
            ui->lbLastRec->setText(statusMsg);
        }
        else
        {
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(httpFinished)
        {
            qDebug()<<"return request " + currentInfno + " ...";
            break;
        }
    }

    if(!httpSuccess)
    {
        // failure then stop operation;
        return ;
    }


    //挂号费用上传
    in = d.object();
    inpu = d.object();
    inpud = d.object();
    putBaseIn(in, "2204");

    QJsonArray jsar;
    QString feedetl_sn = "0";
    qro->exec("select max(Balance_No) from fin_ipr_siinmaininfo "
              " where clinic_code = '" + regClinicCode + "'");
    if(qro->next())
    {
        feedetl_sn = QString::number(qro->value(0).toInt() + 1);
    }

    inpu.insert("feedetl_sn", feedetl_sn);//	费用明细流水号
    inpu.insert("mdtrt_id", ret2201.value("mdtrt_id").toString());//	就诊ID
    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());//	人员编号
    inpu.insert("chrg_bchno", "temp");//	收费批次号
    //inpu.insert("rxno", personBaseinfo.value("psn_no").toString());//	处方号
    inpu.insert("rx_circ_flag", "0");//	外购处方标志
    inpu.insert("fee_ocur_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//	费用发生时间

    qro->exec("select b.med_list_codg, a.fee_code_his from FIN_OPR_REGFEEITEM a, "
              "fin_com_compare b"
              " where a.fee_name ='诊查费' and a.fee_code_his = b.fixmedins_hilist_id");
    qro->next();
    inpu.insert("med_list_codg", qro->value(0).toString());//	医疗目录编码

    inpu.insert("medins_list_codg", qro->value(1).toString() );//	医药机构目录编码
    //inpu.insert("det_item_fee_sumamt",  ui->leYsk->text().toDouble());//	明细项目费用总额
    inpu.insert("det_item_fee_sumamt",  ui->leYsk->text());//	明细项目费用总额
    inpu.insert("cnt", 1);//	数量
    //inpu.insert("pric", ui->leYsk->text().toDouble());//	单价
    inpu.insert("pric", ui->leYsk->text());//	单价
    inpu.insert("bilg_dept_codg", deptCode);//	开单科室编码
    inpu.insert("bilg_dept_name", deptName);//	开单科室名称
    inpu.insert("bilg_dr_codg", docCodeYb);//	开单医生编码
    inpu.insert("bilg_dr_name", docName);//	开单医师姓名
    inpu.insert("hosp_appr_flag", "1");//	医院审批标志

    jsar.append(inpu);

    inpud.insert("feedetail",jsar);
    in.insert("input", inpud);

    indoc.setObject(in);
    qDebug()<< currentInfno + " indoc"<<indoc;

    sq = "update com_business set v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
         " where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    httpSuccess = false;
    httpFinished = false;
    rpl = naManager->post(request, indoc.toJson());
    qDebug()<<"request " + currentInfno + " ...";
    statusMsg = "交易 " + currentInfno + " 。。。";

    while(true)
    {
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty())
        {
            ui->lbLastRec->setText(statusMsg);
        }
        else
        {
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(httpFinished)
        {
            qDebug()<<"retrun request " + currentInfno + " ...";
            break;
        }
    }

    if(!httpSuccess)
    {
        // failure then stop operation;
        return ;//
    }

    //预结算
    in = d.object();
    inpu = d.object();
    inpud = d.object();
    putBaseIn(in, "2206A");

    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());//人员编号
    inpu.insert("mdtrt_cert_type", mdtrt_cert_type);//	就诊凭证类型

    if(mdtrt_cert_type == "03")
    {
        if( "1" == pub::getStr(cardInfo,"|",1) )
        {   //0 社保卡， 1 老医保卡
            inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",8));//老医保卡,8卡号9社保号
        }
        else
        {
            inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",4));   //社保卡,4卡号3社保号
        }
    }
    else if(mdtrt_cert_type == "02")
    {

    }
    else if(mdtrt_cert_type == "01"){

    }

    //inpu.insert("med_type", "12");//医疗类别    12,挂号
    inpu.insert("med_type","11");//	医疗类别
    inpu.insert("medfee_sumamt", ui->leYsk->text());//	医疗费总额
    inpu.insert("psn_setlway", "01");//	个人结算方式
    inpu.insert("mdtrt_id", ret2201.value("mdtrt_id").toString());//	就诊ID
    inpu.insert("chrg_bchno", "temp");//	收费批次号
    inpu.insert("acct_used_flag","1" );//个人账户使用标志
    inpu.insert("insutype", personInsuinfo.value("insutype").toString());//险种类型

    QJsonObject t;
    t.insert("deve_flag","OwnSoft");
    t.insert("dise_reim_mon","");
    t.insert("otp_mulaid_used_flag",otp_mulaid_used_flag_0); //共济标志，  0共济，1不共济。

    inpu.insert("exp_content", t);//	字段扩展
    inpud.insert("data",inpu);
    in.insert("input", inpud);

    indoc.setObject(in);
    qDebug()<< currentInfno + " indoc"<<indoc;
    sq = "update com_business set v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
         " where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    httpSuccess = false;
    httpFinished = false;
    rpl = naManager->post(request, indoc.toJson());
    qDebug()<<"request " + currentInfno + " ...";
    statusMsg = "交易 " + currentInfno + " 。。。";

    while(true)
    {
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty())
        {
            ui->lbLastRec->setText(statusMsg);
        }
        else
        {
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(httpFinished)
        {
            qDebug()<<"retrun request " + currentInfno + " ...";
            break;
        }
    }

    statusMsg = "预结：";
    statusMsg.append("账户支出 ");
    statusMsg.append(QString::asprintf("%.2f",ret2206setlinfo.value("acct_pay").toDouble()));
    statusMsg.append("现金支出 ");
    statusMsg.append(QString::asprintf("%.2f",ret2206setlinfo.value("psn_cash_pay").toDouble()));

    ui->lbLastRec->setText(statusMsg);

}

void Dialog_gh::on_rbReg_clicked()
{
    selectDoctor();
}

void Dialog_gh::on_rbSee_clicked()
{
    selectDoctor();
}

void Dialog_gh::on_pbCbzt_clicked()
{

    QString insuStat = "";    // 医保卡参保状态
    QString psn_type = "";   //人员类别	字符型	6
    QString psn_insu_stas,emp_name,insutype,psn_insu_date,paus_insu_date;
    for(int a = 0; a< personInsuinfoA.size(); a++)
    {
        psn_type = personInsuinfoA[a].toObject().value("psn_type").toString();//人员类别	字符型	6	Y	Y
        psn_insu_stas = personInsuinfoA[a].toObject().value("psn_insu_stas").toString();//人员参保状态	字符型	6	Y
        emp_name = personInsuinfoA[a].toObject().value("emp_name").toString();
        insutype = personInsuinfoA[a].toObject().value("insutype").toString();//险种类型	字符型	6	Y	Y
        psn_insu_date = personInsuinfoA[a].toObject().value("psn_insu_date").toString();//个人参保日期	日期型
        paus_insu_date = personInsuinfoA[a].toObject().value("paus_insu_date").toString();//暂停参保日期	日期型

        qrmt->exec("select dic_label from com_dict_new"
                   " where dic_type = 'PSN_INSU_STAS' and dic_value = '"+psn_insu_stas+"'");
        if(qrmt->next())
        {
            psn_insu_stas=qrmt->value(0).toString();
        }

        qrmt->exec("select dic_label from com_dict_new"
                   " where dic_type = 'INSUTYPE' and dic_value = '"+insutype+"'");
        if(qrmt->next())
        {
            insutype=qrmt->value(0).toString();
        }

        //"人员类别："+险种：+"，日期："+psn_insu_datepsn_type+"，"+状态：停保：
        insuStat += insutype + "，"+psn_insu_stas;
        if(paus_insu_date.isEmpty())
        {
            insuStat += "；\n";
        }
        else
        {
            insuStat += "：" + paus_insu_date + "；\n";
        }
    }

    if(insuStat.isEmpty())
    {
        QMessageBox::information(this,"注意", "缓存中未保留参保信息。");
    }
    else
    {
        QMessageBox::information(this,"参保信息", insuStat);
    }
}

void Dialog_gh::on_pbResetTimeBase_clicked()
{

    if(ui->teBase->time() > QTime::currentTime())
    {
        QMessageBox::information(this, "注意","分诊计时基准设置不可以大于当前时间！");
        return;
    }

    timeBase.setTime(ui->teBase->time());

}


void Dialog_gh::on_pb2001_clicked()
{
    //待遇查询
    QNetworkAccessManager manager ;
    QJsonObject in;
    putBaseIn(  in, "2001") ;

    QJsonObject inpu,inpud;

    inpu.insert("psn_no", personBaseinfo.value("psn_no").toString());//
    inpu.insert("insutype", "310");   //险种类型
    inpu.insert("fixmedins_code", pub::hos_ybbh); //定点医药机构编号
    inpu.insert("med_type", "11"); //医疗类别 普通门诊
    inpu.insert("begntime", QDate::currentDate().toString("yyyy-MM-dd") + " 00:00:00");       //开始时间

    inpud.insert("data",inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);
    qDebug()<<"2001 indoc "<<indoc;

    //保存入参日志
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    QNetworkReply* reply = manager.post(request,indoc.toJson());

    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。

    qDebug()<<" request 2001 is returned";

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid())
    {
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        return ;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError)
    {
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return ;
    }

    QByteArray bt = reply->readAll();
    QString t = QString::fromLocal8Bit(bt);

    QJsonParseError json_error;
    QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);

    if(json_error.error != 0 )
    {
        QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());
        return ;
    }

    qDebug()<< "2001 outDoc "<<jsdc;
    QJsonObject jsob = jsdc.object();

    sq = "update com_business set  tmstmp = now(), v_out = '"
            + jsdc.toJson(QJsonDocument::Compact)
            + "' , infcode = "
            + QString::number(jsob.value("infcode").toInt())
             +  "  where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }

    if(jsob.value("infcode").toInt() != 0)
    {
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意","2001 交易失败：" + t );
        return ;
    }

    QJsonArray jsar = jsob.value("output").toObject().value("trtinfo").toArray();

    QJsonArray::iterator it = jsar.begin();
    QString tmp;
    while(it != jsar.end())
    {
        QString trt_chk_type = it->toObject().value("trt_chk_type").toString();
        QString fund_pay_type = it->toObject().value("fund_pay_type").toString();
        QString trt_enjymnt_flag = it->toObject().value("trt_enjymnt_flag").toString();
        QString trt_chk_rslt ;

        sq = "select dic_label from com_dict_new "
             " where dic_type = 'trt_chk_type' and dic_value = '" + trt_chk_type + "'";
        qrm->exec(sq);
        if(qrm->next())
        {
            trt_chk_type = qrm->value(0).toString();
        }

        sq = "select dic_label from com_dict_new"
             " where dic_type = 'fund_pay_type' and dic_value = '" + fund_pay_type + "'";
        qrm->exec(sq);
        if(qrm->next())
        {
            fund_pay_type = qrm->value(0).toString();
        }

        sq = "select dic_label from com_dict_new"
             " where dic_type = 'trt_enjymnt_flag' and dic_value = '" + trt_enjymnt_flag + "'";
        qrm->exec(sq);
        if(qrm->next())
        {
            trt_enjymnt_flag = qrm->value(0).toString();
        }

        tmp.append(fund_pay_type);
        tmp.append("   ");
        tmp.append(trt_enjymnt_flag);
        tmp.append("   ");
        tmp.append(it->toObject().value("begndate").toString());
        tmp.append("   ");

        if(!it->toObject().value("enddate").toString().isEmpty())
        {
            tmp.append(it->toObject().value("enddate").toString());
        }

        tmp.append("   ");
        tmp.append(it->toObject().value("trt_chk_rslt").toString());
        tmp.append("\n");

        it ++ ;
    }
    QMessageBox::information(this,"查询结果", tmp);
}

void Dialog_gh::on_pb_generate_card_no_clicked()
{
    qro->exec("select SEQ_FIN_REGCARDNO.nextval from dual");
    qro->next();
    max_card_no=qro->value(0).toInt();
    ui->leBzh->setText(QString::number(max_card_no));
    qDebug()<<"申请新病志号："<<ui->leBzh->text()<<"\n";

    ui->pb_generate_card_no->setEnabled(false);
    ui->leBzh->setEnabled(false);

}

void Dialog_gh::on_pb_reg_info_edit_clicked()
{
    info_edit->exec();
}


void Dialog_gh::on_pbGh_clicked()
{

    qDebug()<<"确认保存挂号信息";

    if(!isValid())
    {
        return;
    }

    ui->pbGh->setEnabled(false);  //开始收费流程，按钮禁用。
    qApp->processEvents();  //刷新显示

    reg_item_list.clear();  //票面内容
    //QString fph ;//发票号
    if(pbGhClicked_finished)    //可以申请新发票号
    {
        char errorText[128];
        for(int i = 0; i<128; i++)
        {
            errorText[i] = '0';
        }

        char fpChar[12];
        for(int i = 0; i<12; i++)
        {
            fpChar[i] = '0';
        }
        int errorCode = 0;

        qDebug()<<"申请发票号";
        ui->lbLastRec->setText("申请发票号");
        qApp->processEvents();  //刷新显示
        qro->prepare("CALL PRC_GET_INVOICENO(  'R', :oper, 50, :ivno, :errtext, :errcode, '')");
        qro->bindValue(":oper", pub::usr_code );//操作员Id
        qro->bindValue(":ivno", fpChar, QSql::Out);   //发票号码
        qro->bindValue(":errtext", errorText, QSql::Out);   //错误内容
        qro->bindValue(":errcode", errorCode, QSql::Out);    //错误编号
        qro->exec();
        QString a,b,c;
        a = qro->boundValue(":ivno").toString();
        b = qro->boundValue(":errtext").toString();
        c = qro->boundValue(":errcode").toString();

        if( a.isEmpty())
        {
            QMessageBox::information(this,"错误", "申请发票号失败：" + b );
            ui->pbGh->setEnabled(true);  //恢复按钮状态
            return;
        }

        if(c == "101"){
            QMessageBox::information(this,"注意", "未用发票数量低，请及时请领！" );
        }
        //fph = a;
        cur_fph = a;//发票号
        pbGhClicked_finished = false;   //申请到的发票号在使用之前，不再申请新号
    }

    //qDebug()<<"fph"<<fph;
    reg_item_list << QString("发票号") + "^" + cur_fph;// pub::add0(fph,10);
    reg_item_list << QString("名头") + "^" + pub::hos_name;
    reg_item_list << QString("挂号票") + "^" + "(挂号票)";
    reg_item_list << QString("挂号日期") + "^" + QDate().currentDate().toString("yyyy-MM-dd");
    reg_item_list << QString("门诊号") + "^" + ui->leBzh->text();
    reg_item_list << QString("姓名") + "^" + ui->leXm->text();
    reg_item_list << QString("性别") + "^" + (ui->rbM->isChecked() ? "男" : "女");
    reg_item_list << QString("年龄") + "^" + ui->leNl->text();
    reg_item_list << QString("合计") + "^" + ui->leYsk->text() + "元";
    reg_item_list << QString("科室") + "^" + ui->leGhzs->text();
    reg_item_list << QString("挂号类别") + "^" + ui->cbbGhlb->currentText();
    reg_item_list << QString("挂号时间") + "^" + QDateTime().currentDateTime().toString("HH:mm:ss");
    reg_item_list << QString("收费类别") + "^" + (ui->rbY->isChecked() ? "医保" : "现金");
    reg_item_list << QString("大写") + "^" + pub::bigW(ui->leYsk->text().toDouble());
    reg_item_list << QString("项目明细") + "^" + ui->leGhfmx->text();
    reg_item_list << QString("操作员") + "^" + pub::usr_code;
    reg_item_list << QString("接诊医师") + "^" + docName;
    //以下为非打印项目
    reg_item_list << QString("reglevl_code") + "^" + ghCode;
    reg_item_list << QString("reg_fee") + "^" + ghGhf;
    reg_item_list << QString("diag_fee") + "^" + ghZcf;
    reg_item_list << QString("oth_fee") + "^" + ghGbf;
    reg_item_list << QString("chck_fee") + "^" + "0";

    //提交医保
    bool is_insu = false;
    if(pub::useInsurance && ui->rbY->isChecked())
    {
        ui->lbLastRec->setText("提交医保挂号数据");
        qApp->processEvents();  //刷新显示
        qDebug()<<"医保环境可用，使用医保挂号";
        QString r = ybGh();
        if(r.isEmpty())
        {    //医保操作异常
            qDebug()<<"医保挂号失败";
            ui->pbGh->setEnabled(true);  //恢复按钮状态
            return;
        }

        is_insu = true;

        //返回参数： 费用总额, 帐户支付金额, 现金支付金额, 统筹支付金额, 医疗类别
        reg_item_list << QString("own_cost") + "^"
             + QString::asprintf("%.2f", ret2207setlinfo.value("psn_cash_pay").toDouble()); //现金支付
        reg_item_list << QString("pub_cost") + "^"
             + QString::asprintf("%.2f", ret2207setlinfo.value("fund_pay_sumamt").toDouble());   //基金支付
        reg_item_list << QString("pay_cost") + "^"
             + QString::asprintf("%.2f", ret2207setlinfo.value("acct_pay").toDouble());   //账户支付

        ui->leYskX->setText(QString::asprintf("%.2f", ret2207setlinfo.value("psn_cash_pay").toDouble()));
        ui->leYskY->setText(QString::asprintf("%.2f", ret2207setlinfo.value("acct_pay").toDouble()));
        ui->leYskJ->setText(QString::asprintf("%.2f", ret2207setlinfo.value("fund_pay_sumamt").toDouble()));

        QString t = "现金：" + ui->leYskX->text()
                + " 账户：" + ui->leYskY->text()
                + " 统筹：" + ui->leYskJ->text();

        reg_item_list << QString("医保明细") + "^" + t ;

        double ybys = ui->leYskY->text().toDouble();    //账户支付
        double ybye = mpPerson["ybZhye"].toDouble();                //医保账户余额
        ybye = ybye - ybys;

        if( ybye < 0 || qFuzzyIsNull(ybye))
        {
            ybye = 0; //余额不足或余额为零
        }
        t = "余额：" ;
        t.append( QString::asprintf("%.2f", ybye)); //

        reg_item_list << QString("余额") + "^" + t ;

        mpPerson["Inpatient_No"] = regClinicCode;
        mpPerson["Invoice_No"] = cur_fph;
        mpPerson["Card_No"] = ui->leBzh->text();
        mpPerson["Tot_Cost"] = ui->leYsk->text();
        mpPerson["Dept_Code"] = deptCode;
        mpPerson["Dept_Name"] = deptName;
        mpPerson["Own_Cost"] = QString::asprintf("%.2f", ret2207setlinfo.value("psn_cash_pay").toDouble()); //现金支付
        mpPerson["Pub_Cost"] = QString::asprintf("%.2f", ret2207setlinfo.value("fund_pay_sumamt").toDouble());   //统筹支付
        mpPerson["Pay_Cost"] = QString::asprintf("%.2f", ret2207setlinfo.value("acct_pay").toDouble());   //账户支付
        mpPerson["trans_type"] = "1"; //挂号正交易
        qDebug()<<"willSaveSi";
        ui->lbLastRec->setText("保存医保相关数据");
        qApp->processEvents();  //刷新显示
    }
    else
    {
        qDebug()<<"现金挂号";
        reg_item_list << QString("own_cost") + "^" + ui->leYsk->text(); //现金
        reg_item_list << QString("pub_cost") + "^" + "0";   //统筹
        reg_item_list << QString("pay_cost") + "^" + "0";   //账户
        ui->leYskX->setText(ui->leYsk->text());
        ui->leYskY->setText("0");
        ui->leYskJ->setText("0");
        reg_item_list << QString("医保明细") + "^" +  "现金 " + ui->leYsk->text() ;    //现金挂号，只打印应收款
    }
    qDebug()<<"保存挂号信息";
    ui->lbLastRec->setText("保存挂号主表信息");
    qApp->processEvents();  //刷新显示

    if(!save( is_insu))
    {
        return;
    }

    qDebug()<<"打印挂号票\n";
    ui->lbLastRec->setText("打印挂号票");
    qApp->processEvents();  //刷新显示
    printOut(reg_item_list);
    qDebug()<<"清屏\n";
    on_pbClrScr_clicked(); //清屏
    //取下一个就诊流水号
    qro->exec("select seq_fin_clinicno.nextval from dual");
    qro->next();

    regClinicCode = qro->value(0).toString();

    ui->pbGh->setEnabled(true);  //恢复按钮状态
    qDebug()<<"取下一个可用的clinic_code"<<regClinicCode<<"\n";
}

void Dialog_gh::on_pbYbdk_clicked()
{

    mdtrt_cert_type = "03"; //就诊凭证类型

    qDebug()<<"通过读卡器读医保卡信息\n";

    statusMsg = "医保卡有效性验证。。。";

    connect(ybBusiness, SIGNAL(resultReady(int, QString, QString)),
            this, SLOT(handleRet(int, QString, QString)));

    //卡机开始读卡

    emit opThread(mdtrt_cert_type.toInt() , "QString");    // 发送信号触发线程 , 执行 ReadCardBas

    businessFinish = false;
    while(true)
    {
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty())
        {
            ui->lbLastRec->setText(statusMsg);
        }
        else
        {
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(businessFinish){
            break;
        }
    }

    if(businessRetVal == 0)
    {
        QString ret1 = businessRetStr1; //获取出参
        QString ret2 = businessRetStr2; //获取出参

        cardInfo = businessRetStr1;
        busiCardInfo= businessRetStr2;
        qDebug()<<"ret1 = "<<ret1;
        qDebug()<<"ret2 = "<<ret2;
        qDebug()<<"\n";

        sq = "insert into com_business "
             "(tmstmp,ywbh,user,jysj,jyfs,v_in,v_out) values "
             "(now(),'cardRead','%1',DATE_FORMAT(now(),'%Y-%m-%d %T'),"
             "'card','','%2^%3')";
        sq = sq.arg(pub::usr_code).arg(ret1).arg(ret2);

        if(!qrm->exec(sq))
        {
            QMessageBox::information(this,"注意","保存医保动态库交易日志失败！ ");
            qDebug()<<sq;
        }

        QJsonObject in;
        putBaseIn(  in, "1101")        ;

        QJsonObject inpu,inpud;
        QString sfzh;//身份证号

        inpu.insert("mdtrt_cert_type", mdtrt_cert_type);   //就诊凭证类别
        if( "1" == pub::getStr(cardInfo,"|",1) )
        {
            //0 社保卡， 1 老医保卡
            if(pub::getStr(cardInfo,"|",8).isEmpty())
            {
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",9)
                            + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            }
            else
            {
                inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",8)
                            + "|" + busiCardInfo);//老医保卡,8卡号9社保号
            }
            sfzh = pub::getStr(cardInfo,"|",9);
            inpu.insert("psn_name", pub::getStr(cardInfo,"|",10)); //人员姓名
            inpu.insert("card_sn",pub::getStr(cardInfo,"|",2)); //卡识别码
            inpu.insert("certno", pub::getStr(cardInfo,"|",9));      //证件号码
            inpu.insert("psn_cert_type","01");       //人员证件类型  固定？
        }
        else
        {
            inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",4)
                        + "|" + busiCardInfo);   //社保卡,4卡号3社保号
            inpu.insert("psn_name", pub::getStr(cardInfo,"|",6)); //人员姓名
            inpu.insert("card_sn",pub::getStr(cardInfo,"|",5)); //卡识别码
            inpu.insert("certno", pub::getStr(cardInfo,"|",3));      //证件号码
            inpu.insert("psn_cert_type","01");       //人员证件类型  固定？
            sfzh = pub::getStr(cardInfo,"|",3);
        }

        inpud.insert("data",inpu);
        in.insert("input", inpud);

        QJsonDocument indoc ;
        indoc.setObject(in);

        sq = "update com_business set jyfs = 'cardRead', v_in = '%1' where jyls = '%2'";
        sq = sq.arg(QString::fromLocal8Bit(indoc.toJson(QJsonDocument::Compact)))
                .arg(currentMsgid);

        if(!qrm->exec(sq))
        {
            QMessageBox::information(this,"错误","保存入参日志失败！");
            qDebug()<<sq;
        }

        qDebug()<<" 1101 indoc"<<indoc;

        QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
        connect(naManager, SIGNAL(finished(QNetworkReply*)),
                this, SLOT(postRequestFinished(QNetworkReply*)));

        httpSuccess = false;
        httpFinished = false;
        rpl = naManager->post(request, indoc.toJson());
        qDebug()<<"request 1101 ...";
        statusMsg = "交易1101。。。";
        while(true)
        {
            QThread::msleep(330);
            if( ui->lbLastRec->text().isEmpty())
            {
                ui->lbLastRec->setText(statusMsg);
            }
            else
            {
                ui->lbLastRec->setText("");
            }
            qApp->processEvents();
            if(httpFinished)
            {
                disconnect(naManager, SIGNAL(finished(QNetworkReply*)),
                           this, SLOT(postRequestFinished(QNetworkReply*)));
                qDebug()<<"return request 1101 ...";
                break;
            }
        }

        if(httpSuccess)
        {
            qDebug()<<"1101 return success.";
            readRetVal("");
            //用身份证号检索挂号记录
            getRegRec("y", personBaseinfo.value("certno").toString(), "" );
        }

    }
    else
    {
        QMessageBox::information(this,"错误","医保读卡失败！ ");
        qDebug()<<"医保读卡失败";
    }
}

void Dialog_gh::on_pbYbsm_clicked()
{

    qDebug()<<"读医保二维码";
    mdtrt_cert_type = "01"; //就诊凭证类型

    statusMsg = "医保卡有效性验证。。。";

    connect(ybBusiness, SIGNAL(resultReady(int, QString, QString)),
            this, SLOT(handleRet(int, QString, QString)));

    //开始读卡

    QJsonDocument d;    //清空QJsonObject之用
    QJsonObject in; //入参
    QJsonObject inpu,inpud; // 入参 input 段
    QJsonDocument indoc;

    inpu.insert("businessType", "01101");     //用码类型，挂号
    inpu.insert("officeId", pub::dp_code);
    inpu.insert("officeName", pub::dp_name);
    inpu.insert("operatorId", pub::usr_code);
    inpu.insert("operatorName", pub::usr_name);
    inpu.insert("orgId", pub::hos_ybbh);

    in.insert("data", inpu);

    in.insert("orgId", pub::hos_ybbh);
    in.insert("transType", "ec.query");

    indoc.setObject(in);

    emit opThread(mdtrt_cert_type.toInt() , indoc.toJson());    // 发送信号触发线程

    qDebug()<<"扫码 "<<indoc;

    businessFinish = false;
    while(true)
    {
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty())
        {
            ui->lbLastRec->setText(statusMsg);
        }
        else
        {
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(businessFinish)
        {
            break;
        }
    }

    if(businessRetVal == 0)
    {
        QString ret1 = businessRetStr1; //获取出参

        QJsonParseError json_error;
        QJsonDocument jsdc = QJsonDocument::fromJson(ret1.toUtf8(), &json_error);
        if(json_error.error != 0 )
        {
            QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());
            return ;
        }
        qDebug()<< "scan code outDoc "<<jsdc;

        sq = "insert into com_business (tmstmp,ywbh,user,jysj,jyfs,v_in,v_out) values "
             "(now(),'codeScan','" + pub::usr_code + "',DATE_FORMAT(now(),'%Y-%m-%d %T'),'code','"
                + indoc.toJson(QJsonDocument::Compact) + "','" + ret1 + "')";
        if(!qrm->exec(sq))
        {
            QMessageBox::information(this,"注意","保存医保动态库交易日志失败！ ");
            qDebug()<<sq;
        }

        QJsonObject jsob = jsdc.object();

        if( !qFuzzyCompare(jsob.value("code").toDouble() , 0))
        {
            QMessageBox::information(this,"注意","动态库返回失败: " + jsob.value("message").toString());
            return;
        }

        retScan = jsob.value("data").toObject();

        QJsonObject in;
        putBaseIn(  in, "1101")        ;

        QJsonObject inpu,inpud;
        QString sfzh;//身份证号

        inpu.insert("mdtrt_cert_type", mdtrt_cert_type);   //就诊凭证类别

        inpu.insert("mdtrt_cert_no", retScan.value("ecToken").toString());   //社保卡,4卡号3社保号
        inpu.insert("psn_name", retScan.value("userName").toString()); //人员姓名

        inpu.insert("certno", retScan.value("idNo").toString() );      //证件号码
        inpu.insert("psn_cert_type","01");       //人员证件类型  固定？
        sfzh = retScan.value("idNo").toString();

        inpud.insert("data",inpu);
        in.insert("input", inpud);

        QJsonDocument indoc ;
        indoc.setObject(in);

        sq = "update com_business set jyfs = 'codeScan',"
             " v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
             " where jyls = '" + currentMsgid + "'";

        if(!qrm->exec(sq))
        {
            QMessageBox::information(this,"错误","保存入参日志失败！");
            qDebug()<<sq;
        }
        qDebug()<<" 1101 indoc"<<indoc;

        QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
        connect(naManager, SIGNAL(finished(QNetworkReply*)),
                this, SLOT(postRequestFinished(QNetworkReply*)));

        httpSuccess = false;
        httpFinished = false;
        rpl = naManager->post(request, indoc.toJson());
        qDebug()<<"request 1101 ...";
        statusMsg = "交易1101。。。";
        while(true)
        {
            QThread::msleep(330);
            if( ui->lbLastRec->text().isEmpty())
            {
                ui->lbLastRec->setText(statusMsg);
            }
            else
            {
                ui->lbLastRec->setText("");
            }
            qApp->processEvents();
            if(httpFinished)
            {
                disconnect(naManager, SIGNAL(finished(QNetworkReply*)),
                           this, SLOT(postRequestFinished(QNetworkReply*)));
                qDebug()<<"return request 1101 ...";
                break;
            }
        }

        if(httpSuccess)
        {
            qDebug()<<"1101 return success.";
            readRetVal("");
            getRegRec("y", personBaseinfo.value("certno").toString() , ""); //读取挂号记录

        }

    }else {
        QMessageBox::information(this,"错误","医保扫码失败！ ");
        qDebug()<<"医保扫码失败";
    }

}

void Dialog_gh::on_pbDsfz_clicked()
{

    mdtrt_cert_type = "02"; //就诊凭证类型

    qDebug()<<"读身份证";

    statusMsg = "医保卡有效性验证。。。";

    connect(ybBusiness, SIGNAL(resultReady(int, QString, QString)),
            this, SLOT(handleRet(int, QString, QString)));

    //卡机开始读卡

    emit opThread(mdtrt_cert_type.toInt() , "QString");    // 发送信号触发线程 , 执行 ReadCardBas

    businessFinish = false;
    while(true)
    {
        QThread::msleep(330);
        if( ui->lbLastRec->text().isEmpty())
        {
            ui->lbLastRec->setText(statusMsg);
        }
        else
        {
            ui->lbLastRec->setText("");
        }
        qApp->processEvents();
        if(businessFinish)
        {
            break;
        }
    }

    if(businessRetVal == 0){

        QString ret1 = businessRetStr1; //获取出参
        QString ret2 = businessRetStr2; //获取出参

        cardInfo = businessRetStr1;
        busiCardInfo= businessRetStr2;
        qDebug()<<"ret1 = "<<ret1;
        qDebug()<<"ret2 = "<<ret2;


        sq = "insert into com_business (tmstmp,ywbh,user,jysj,jyfs,v_in,v_out) values "
             "(now(),'idRead','" + pub::usr_code + "',DATE_FORMAT(now(),'%Y-%m-%d %T'),'id','','"
                + ret1 + "^" + ret2 + "')";
        if(!qrm->exec(sq))
        {
            QMessageBox::information(this,"注意","保存医保动态库交易日志失败！ ");
            qDebug()<<sq;
        }

        QJsonObject in;
        putBaseIn(in, "1101");

        QJsonObject inpu,inpud;
        QString sfzh;//身份证号

        inpu.insert("mdtrt_cert_type", mdtrt_cert_type);   //就诊凭证类别
        inpu.insert("mdtrt_cert_no", pub::getStr(cardInfo,"|",2) + "|" + busiCardInfo);   //社保卡,4卡号3社保号
        inpu.insert("psn_name", pub::getStr(cardInfo,"|",5)); //人员姓名
        inpu.insert("certno", pub::getStr(cardInfo,"|",2));      //证件号码
        inpu.insert("psn_cert_type","01");       //人员证件类型  固定？
        sfzh = pub::getStr(cardInfo,"|",2);

        inpud.insert("data",inpu);
        in.insert("input", inpud);

        QJsonDocument indoc ;
        indoc.setObject(in);

        sq = "update com_business set jyfs = 'idRead',"
             " v_in = '" + indoc.toJson(QJsonDocument::Compact) + "'"
             " where jyls = '" + currentMsgid + "'";

        if(!qrm->exec(sq))
        {
            QMessageBox::information(this,"错误","保存入参日志失败！");
            qDebug()<<sq;
        }

        qDebug()<<" 1101 indoc"<<indoc;

        QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
        connect(naManager, SIGNAL(finished(QNetworkReply*)),
                this, SLOT(postRequestFinished(QNetworkReply*)));

        httpSuccess = false;
        httpFinished = false;
        rpl = naManager->post(request, indoc.toJson());
        qDebug()<<"request 1101 ...";
        statusMsg = "交易1101。。。";
        while(true)
        {
            QThread::msleep(330);
            if( ui->lbLastRec->text().isEmpty())
            {
                ui->lbLastRec->setText(statusMsg);
            }
            else
            {
                ui->lbLastRec->setText("");
            }
            qApp->processEvents();
            if(httpFinished)
            {
                disconnect(naManager, SIGNAL(finished(QNetworkReply*)),
                           this, SLOT(postRequestFinished(QNetworkReply*)));
                qDebug()<<"return request 1101 ...";
                break;
            }
        }

        if(httpSuccess)
        {
            qDebug()<<"1101 return success.";
            readRetVal("");
            getRegRec("y", personBaseinfo.value("certno").toString() , ""); //读取挂号记录

        }
        else
        {
            //读身份证返回信息格式：
            //发卡地区行政区划代码（卡识别码前6位）|社会保障号码（身份证号）|卡号|卡识别码|姓名|
            //卡复位信息（仅取历史字节）|规范版本|发卡日期|有效期|终端机编号|终端设备号|性别|民族|
            //出生日期|地址|签发机关|照片BASE64|。

            //医保操作失败，直接显示信息，以现金模式挂号

            ui->leXm->setText(pub::getStr(cardInfo,"|", 5));
            QString s = pub::getStr(cardInfo,"|", 12);
            //if(s == "1"){
            if(s == "男")
            {
                ui->rbM->setChecked(true);
            }
            else
            {
                ui->rbFM->setChecked(true);
            }

            ui->leSfzh->setText(pub::getStr(cardInfo,"|", 2));

            QStringList sl = pub::getNl(pub::getStr(cardInfo,"|", 14));
            if(!sl.isEmpty())
            {
                if(sl[0].toInt() >= 70)
                {//
                    ui->cbbGhlb->setCurrentText("老年号");
                }
                ui->leNl->setText(sl[0]+sl[1]);
            }

            cardReaded = true;

            ui->rbX->setChecked(true);
            getRegRec("s",ui->leSfzh->text().trimmed().toUpper(),"");
        }

    }
    else
    {
        QMessageBox::information(this,"错误","读取身份证失败！ ");
        qDebug()<<"身份证读卡失败";
    }
}

void Dialog_gh::on_leBzh_returnPressed()
{

    qDebug()<<"使用病志号方式检索"<<ui->leBzh->text();

    if(ui->leBzh->text().isEmpty())
    {
        qDebug()<<"病志号空, rela_phone : " << mpPerson["rela_phone"] ;
        mpPerson["rela_phone"] = "";    //清除联系电话
        return;
    }

    int card_no_input, card_no_max;

    qro->exec("SELECT LAST_NUMBER FROM USER_SEQUENCES"
              " WHERE SEQUENCE_NAME = 'SEQ_FIN_REGCARDNO'");
    qro->next();

    card_no_max = qro->value(0).toInt();
    card_no_input = ui->leBzh->text().trimmed().toInt();

    if(card_no_input == 0 || card_no_max < card_no_input)
    {
        QMessageBox::information(this, "注意", "病志号输入不合理！");
        return;
    }

    ui->leBzh->setText(pub::add0(ui->leBzh->text().trimmed(),10));

    sq = "select r.name, r.birthday, r.sex_code, r.idenno, r.pact_code, r.mcard_no,"//0-5
         "r.dept_name, r.clinic_code, r.doct_name, r.card_type, r.reglevl_name, "//6-10
         " to_char(r.reg_date ,'yyyy-mm-dd hh24:mi:ss'), r.ynsee, r.valid_flag, "//11-13
         " r.rowid, r.rela_phone , r.reg_date"//14-16
         " from fin_opr_register r "
         " where r.valid_flag = '1' and r.card_no = '" + ui->leBzh->text() + "' "
         " order by r.reg_date desc"; //and r.dept_code like '%" + deptCode + "%'
    //对应病志号最后一条有效挂号记录。
    if(!qro->exec(sq))
    {
        QMessageBox::information(this,"error","SQL is : "+sq);
        qDebug()<<"error"<<sq;
        return;
    }

    qro->next();

    ynfr = '1'; // 预设置初诊标志

    if(qro->isNull(0))
    {
        //has no register record.
        last_dept = "";
        qDebug()<<"新病志号："<<ui->leBzh->text()<<"\n";
        //qDebug()<<" rela_phone : " << mpPerson["rela_phone"] ;
        mpPerson["rela_phone"] = "";    //联系电话

        return;
    }

    last_dept = qro->value("dept_name").toString();

    //
    if(mpPerson["ybXm"].isEmpty())
    {
       mpPerson["ybXm"] = qro->value(0).toString();//姓名
    }

    if(mpPerson["ybXb"].isEmpty())
    {
        mpPerson["ybXb"] = qro->value(2).toString();//性别  二级代码 1 男 2 女
        (mpPerson["ybXb"] == "M" || mpPerson["ybXb"] == "1")
                ? ui->rbM->setChecked(true)
                : ui->rbFM->setChecked(true);    //sex_code
    }


    mpPerson["rela_phone"] = qro->value(15).toString();// 联系电话
    deptName = qro->value(6).toString();    //last regist department
    QString lastRec = "最近挂号：" + deptName + " " +  qro->value(11).toString();
    ui->lbLastRec->setText(lastRec);

    //2024-3-7
    //用检索到的姓名替换当前显示姓名
    ui->leXm->setText(mpPerson["ybXm"]); //name

    if(ui->leSfzh->text().trimmed().isEmpty())
    {
        if(mpPerson["ybSfzh"].isEmpty())
        {
            mpPerson["ybSfzh"] = qro->value(3).toString();    //身份证号
        }
        ui->leSfzh->setText(mpPerson["ybSfzh"]); //identify card
    }

    if(mpPerson["ybCsrq"].isEmpty())
    {   //
        if(ui->leSfzh->text().trimmed().length() == 18)
        {
            //身份证号有效，从身份证号提取出生日期。
            mpPerson["ybCsrq"] = ui->leSfzh->text().mid(6,8);
        }
        else
        {
            //使用上次挂号数据
            QDate dt = qro->value(1).toDate();
            mpPerson["ybCsrq"] = dt.toString("yyyyMMdd");//出生日期
        }
    }

    QStringList ag = pub::getNl(mpPerson["ybCsrq"]);

    if(ag.size() >0 && ui->leNl->text().isEmpty())
    {
        if(ag[0].toInt() >= 70)
        {//
            ui->cbbGhlb->setCurrentText("老年号");
        }
        ui->leNl->setText(ag[0]+ag[1]);     //age
    }

    if(ui->leYbkh->text().isEmpty())
    {
        ui->leYbkh->setText(mpPerson["ybGrbh"]);     //card number
    }

    ui->leGhzs->setText(deptName);
    qDebug()<<"检索挂号科室代码";
    foreach(QString i, dept_name_code)
    { //
        if(pub::getStr(i,"^",1) == deptName)
        {
            deptCode = pub::getStr(i,"^",2);  //代码
            default_diag_code = pub::getStr(i,"^",3);  //诊室默认诊断
            default_diag_name = pub::getStr(i,"^",4);  //诊室默认诊断
            break;
        }
    }
    qDebug()<<"设置医生列表";
    qDebug()<<"病志号存在历史挂号记录，设置界面模式为retbzh";
    setState("retbzh");

    //医保患者涉及结算问题，挂号与缴费信息不一致可能产生意外，所以不允许变更
    if( "0" == qro->value(12).toString() //未接诊
            && "1" == qro->value(13).toString()//未退费
            && "1" == qro->value(4).toString()//现金患者
            )
    {
        //最后一个号有效且未用
        ui->pbGhtp->setEnabled(true);
        mpPerson["rowid"] = qro->value(14).toString();
        mpPerson["previous_doct_name"] = qro->value(8).toString();
        mpPerson["previous_dept_name"] = deptName;
        mpPerson["previous_patient_name"] = qro->value(0).toString();
    }
    selectDoctor(); //

}

void Dialog_gh::on_twDpList_itemClicked(QTableWidgetItem *itm)
{

    qDebug()<<"诊室列表单击，提取诊室代码和关联医生信息";
    if(itm->text().isEmpty())
    {
        QMessageBox::information(this,"注意","诊室无效！");
        return;
    }

    ui->leGhzs->setText(itm->text());   //显示选定的诊室
    ui->leJzys->setText("");        //清除选定的医生
    deptName = itm->text();     //查找诊室代码
    foreach(QString i, dept_name_code)
    {
        if(pub::getStr(i,"^",1) == deptName)
        {
            deptCode = pub::getStr(i,"^",2);  //诊室代码
            default_diag_code = pub::getStr(i,"^",3);  //诊室默认诊断
            default_diag_name = pub::getStr(i,"^",4);  //诊室默认诊断
            break;
        }
    }
    selectDoctor();     //按照预定规则选择接诊医生
}

bool Dialog_gh::save( bool is_insu)
{
    qDebug()<<"save 保存挂号数据"<<ui->leBzh->text();

    //保存患者基础信息
    if(!save_patient_base())
    {
        return false;
    }

    pub::db_o.transaction();

    //保存基本挂号信息
    if(!save_reg())
    {
        pub::db_o.rollback();
        return false;
    }

    //保存医保相关信息
    if(is_insu && !saveSI())
    {
        pub::db_o.rollback();
        return false;
    }

    pub::db_o.commit();
    //pub::db_o.rollback();

    return true;
}

bool Dialog_gh::save_reg()
{
    //获取挂号处方号
    sq = "select name from com_dictionary where oper_code = '"
            + pub::usr_code + "' and type = 'RegRecipeNo'";
    qDebug()<<"获取当前挂号处方号 : "<<sq<<"\n";
    qro->exec(sq);
    qro->next();
    QString regRecNo = qro->value(0).toString();

    sq = "update com_dictionary set name = '%1'"
         " where oper_code = '%2'  and type = 'RegRecipeNo'";
    sq = sq.arg(QString::number(regRecNo.toInt() + 1))
            .arg(pub::usr_code);
    qDebug()<<"保存下一个挂号处方号 : "<<sq<<"\n";
    qro->exec(sq);

    sq = "insert into fin_opr_register "
         "( medfee_paymtd,ynbook,medical_type,ynfr,balance_flag,recipe_no,"
         "clinic_code,trans_type,card_no,reg_date,name,"
         "idenno,sex_code,birthday,card_type,paykind_code,pact_code,pact_name,"
         "mcard_no,reglevl_code,"
         "reglevl_name,dept_code,dept_name,order_no,seeno,invoice_no,"
         "reg_fee,chck_fee,diag_fee,oth_fee,own_cost,pub_cost,pay_cost,valid_flag,oper_code,"
         "oper_date, ynsee, doct_code, doct_name,  rela_phone) "
         "values (";
    //sq += "'" +  + "',";
    QString t = ui->rbX->isChecked() ? "07" : "01";
    sq += "'" + t + "','1','1',";//医疗费用支付方式//挂号方式，1 现场挂号//挂号类别，1 普通门诊
    sq += "'" + ynfr + "','0',";// 初复诊标志
    sq += "'" + regRecNo + "',";//":recipe_no,"
    sq += "'" + regClinicCode + "','1',";//":clinic_code,
    sq += "'" + ui->leBzh->text() + "',sysdate,";//:card_no
    sq += "'" + ui->leXm->text() + "',"; //":name,"
    sq += "'" + ui->leSfzh->text().trimmed() + "',";//":idenno,"

    t = ui->rbM->isChecked() ? "M" : "F";
    sq += "'" + t + "',"; //":sex_code,"

    if(ui->leSfzh->text().trimmed().length() == 18)
    {
        //身份证号有效，从身份证号提取出生日期。否则从年龄估算。
        t = ui->leSfzh->text().trimmed().mid(6,8);
    }
    else
    {
        t = pub::getBirth(ui->leNl->text());
    }

    sq += "to_date('" + t + "','yyyymmdd'),'01',";//birthday, card_type
    t = ui->rbX->isChecked() ? "1" : "2";
    sq += "concat('0','" + t + "'),";//paykind
    sq += "'" + t + "',";//":pact_code,"

    t = ui->rbX->isChecked() ? "现金" : "沈阳市保";
    sq += "'" + t + "',";//":pact_name,"

    sq += "'" + ui->leYbkh->text() + "',";//":mcard_no,"
    sq += "'" + ghCode + "',";//":reglevel_code,"
    sq += "'" + ghType + "',";//":reglevl_name,"
    sq += "'" + deptCode + "',";//":dept_code,"
    sq += "'" + deptName + "',";//":dept_name,
    sq += "get_reg_sn('ALL'),get_reg_sn('" + deptCode + "'),";

    t = pub::getValueFromList(reg_item_list, "发票号");
    sq += "'" + t + "',";//":invoice_no,"

    sq += "'" + pub::getValueFromList(reg_item_list, "reg_fee") + "',";//":reg_fee,"
    sq += "'" + pub::getValueFromList(reg_item_list, "chck_fee") + "',";//":chck_fee,"
    sq += "'" + pub::getValueFromList(reg_item_list, "diag_fee") + "',";//":diag_fee,"
    sq += "'" + pub::getValueFromList(reg_item_list, "oth_fee") + "',";//":oth_fee,"
    sq += "'" + pub::getValueFromList(reg_item_list, "own_cost") + "',"; //":own_cost,"
    sq += "'" + pub::getValueFromList(reg_item_list, "pub_cost") + "',";//":pub_cost,"
    sq += "'" + pub::getValueFromList(reg_item_list, "pay_cost") + "',";//":pay_cost,'1',"
    sq += "'1'，'" + pub::usr_code + "',sysdate,'0',";//":oper_code,"
    sq += "'" + docCode + "',";   //":doct_code, "
    sq += "'" + docName + "',";   //":doct_name,"
    sq += "'" + mpPerson["rela_phone"] + "'"; //联系电话
    sq += ")" ;

    qDebug()<<"保存挂号记录："<<sq<<"\n";

    pub::db_o.exec(sq);
    if(pub::db_o.lastError().isValid())
    {
        QMessageBox::information(this,"错误","插入数据表“fin_opr_register”错误！");
        qDebug()<<pub::db_o.lastError().text();
        return false;
    }

    return true;
}

bool Dialog_gh::saveSI()
{
    qDebug()<<"保存医保相关挂号信息";
    //医保对账需要保存必要信息

    int blance_no = 0;  //挂号的balance_no只能是 0

    sq = "insert into fin_ipr_siinmaininfo ("
         " insutype, clr_type, clr_way, hifp_pay, med_type, medfee_sumamt, preselfpay_amt, "
         " inscp_scp_amt, psn_cash_pay, fund_pay_sumamt, acct_pay, acct_mulaid_pay, psn_type,"
         "insuplc_admdvs,psn_no,mdtrt_id,ipt_otp_no,msgid,setl_id,mdtrt_cert_type,"
         "individualbalance,trans_type,Inpatient_No,"
         "Balance_No,Invoice_No,Medical_Type,Patient_No,"
         "Card_No,Mcard_No,App_No,Procreate_Pcno,Si_Begindate,Si_State,Name,"
         "Sex_Code,Idenno,Spell_Code,Birthday,Empl_Type,Work_Name,Clinic_Diagnose,"
         "Dept_Code,Dept_Name,Paykind_Code,Pact_Code,Pact_Name,Bed_No,In_Date,"
         "In_Diagnosedate,In_Diagnose,In_Diagnosename,Oper_Code,Oper_Date,"
         "Reg_No,Fee_Times,Hos_Cost,Year_Cost,Out_Date,Out_Diagnose,"
         "Out_Diagnosename,Balance_Date,Tot_Cost,Pay_Cost,Pub_Cost,Item_Paycost,"
         "Base_Cost,Item_Ylcost,Item_Paycost2,Own_Cost,Over_Cost,Valid_Flag,"
         "Balance_State,Remark,Official_Cost,Type_Code,Person_Type,"
         "Primarydiagnosecode,Operatecode1,Operatecode2,Operatecode3,"
         "Primarydiagnosename,overtake_owncost,BUSINESSSEQUENCE,"
         "SERIOUSILLNESS_IN_COST,SERIOUSILLNESS_COST,SERIOUSILLNESS_TOTAL"
         ") values(";
    sq += "'" + ret2207setlinfo.value("insutype").toString() + "',";
    sq += "'" + ret2207setlinfo.value("clr_type").toString() + "',";
    sq += "'" + ret2207setlinfo.value("clr_way").toString() + "',";
    sq += "'" + QString::asprintf("%.2f",ret2207setlinfo.value("hifp_pay").toDouble()) + "',";
    sq += "'" + ret2207setlinfo.value("med_type").toString() + "',";
    sq += "'" + QString::asprintf("%.2f",ret2207setlinfo.value("medfee_sumamt").toDouble()) + "',";
    sq += "'" + QString::asprintf("%.2f",ret2207setlinfo.value("preselfpay_amt").toDouble()) + "',";
    sq += "'" + QString::asprintf("%.2f",ret2207setlinfo.value("inscp_scp_amt").toDouble()) + "',";
    sq += "'" + QString::asprintf("%.2f",ret2207setlinfo.value("psn_cash_pay").toDouble()) + "',";
    sq += "'" + QString::asprintf("%.2f",ret2207setlinfo.value("fund_pay_sumamt").toDouble()) + "',";
    sq += "'" + QString::asprintf("%.2f",ret2207setlinfo.value("acct_pay").toDouble()) + "',";
    sq += "'" + QString::asprintf("%.2f",ret2207setlinfo.value("acct_mulaid_pay").toDouble()) + "',";
    sq += "'" + ret2207setlinfo.value("psn_type").toString() + "',";
    sq += "'" + personInsuinfo.value("insuplc_admdvs").toString() + "',";
    sq += "'" + ret2201.value("psn_no").toString() + "',";
    sq += "'" + ret2201.value("mdtrt_id").toString() + "',";
    sq += "'" + ret2201.value("ipt_otp_no").toString() + "',";
    sq += "'" + msgid2207 + "',";
    sq += "'" + ret2207setlinfo.value("setl_id").toString() + "',";
    sq += "'" + mdtrt_cert_type + "',";
    sq += "'" + QString::asprintf("%.2f",ret2207setlinfo.value("balc").toDouble()) + "',";
    sq += "'" + mpPerson["trans_type"] + "',";//交易类型，1正2负
    sq += "'" + mpPerson["Inpatient_No"] + "',";//住院流水号,clinic_code
    sq += "'" + QString::number(blance_no) + "',";//结算序号
    sq += "'" + mpPerson["Invoice_No"] + "','11','',";//发票号
    sq += "'" + mpPerson["Card_No"] + "',";//就诊卡号
    sq += "'" + mpPerson["ybGrbh"] + "',";//医疗证号
    sq += "'0','',To_Date('0001/1/1', 'YYYY-MM-DD'),'',";
    sq += "'" + mpPerson["ybXm"] + "',";//姓名
    QString t = mpPerson["ybXb"] == "1" ? "M" : "F";
    sq += "'" + t + "',"; //性别
    sq += "'" + mpPerson["ybSfzh"] + "','',";//身份证号
    sq += "to_date('" + mpPerson["ybCsrq"] + "','yyyy-mm-dd'),'','','',";//生日
    sq += "'" + mpPerson["Dept_Code"] + "',";//科室代码
    sq += "'" + mpPerson["Dept_Name"] + "',"; //科室名称
    sq += "'02','2','沈阳市保','',sysdate,sysdate,'','',";//结算类别 1-自费  2-保险,//合同代码,);//合同单位名称
    sq += "'" + pub::usr_code + "',sysdate,";//操作员
    sq += "'" + mpPerson["ybSbkh"] + "',0,0,0,sysdate,'','',To_Date('0001/1/1', 'yyyy-mm-dd'),";//社保卡号
    sq += "'" + mpPerson["Tot_Cost"] + "',";//合计金额
    sq += "'" + mpPerson["Pay_Cost"] + "',"; //账户支付
    sq += "'" + mpPerson["Pub_Cost"]+ "',0,0,0,0,"; //基金支付
    sq += "'" + mpPerson["Own_Cost"]+ "', 0, '1', '1',"; //个人支付
    sq += "'" + mpPerson["ybXzlx"] + "','0','1',"; //险种类别2100返回
    sq += "'" + mpPerson["ybYldylb"] + "',";//医疗待遇类别2100返回
    sq += "'','','','','','0','',0,0,0)";

    qDebug()<<"保存医保数据 siinmaininfo : "<<sq<<"\n";

    pub::db_o.exec(sq);
    if(pub::db_o.lastError().isValid())
    {
        QMessageBox::information(this,"错误","插入 fin_ipr_siinmaininfo 失败！");
        qDebug()<<pub::db_o.lastError().text();
        return false;
    }

    return true;
}

bool Dialog_gh::save_patient_base()
{
    sq = "select card_no from com_patientinfo where card_no ='" + ui->leBzh->text() + "'";
    qro->exec(sq);

    if(qro->next())
    {
        return true;
    }

    mpPerson["rela_phone"] = "";  //清空联系电话。首诊，界面不录入电话。
    qDebug()<<"查询返回空，首诊患者，保存记录到 com_patientinfo";
    sq = "insert into com_patientinfo (pact_name,idenno,card_no,"
         "name,birthday,sex_code,pact_code,"
         "fir_see_date,oper_code,oper_date) "
         "values"
         " ('%1','%2','%3','%4',"//:pact_name,:idenno,:card_no,:name
            " to_date('%5','yyyymmdd'),"//:birthday,
            "'%6','%7',sysdate,'%8',sysdate)";//:sex_code,:pact_code,:oper_code

    QString dt_str ;
    if(ui->leSfzh->text().trimmed().length() == 18)
    {
        //身份证号有效，从身份证号提取出生日期。否则从年龄估算。
        dt_str = ui->leSfzh->text().trimmed().mid(6,8);
    }
    else
    {
        dt_str = pub::getBirth(ui->leNl->text());
    }

    sq = sq.arg(ui->rbX->isChecked() ? "现金" : "沈阳市保")
            .arg(ui->leSfzh->text().trimmed().toUpper())
            .arg(ui->leBzh->text())
            .arg(ui->leXm->text())
            .arg(dt_str)
            .arg(ui->rbM->isChecked() ? "M" : "F")
            .arg(ui->rbX->isChecked() ? "1" : "2")
            .arg(pub::usr_code);

    qDebug()<<"保存患者基础信息："<<sq<<"\n";
    if(!qro->exec(sq))
    {
        QMessageBox::information(this,"错误","插入数据表“com_patientinfo”错误！");
        qDebug()<<qro->lastError().text();
        return false;
    }

    return true;
}

